{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OJlsC1VUOcPW"
      },
      "source": [
        "# **Context Engineering with [Pixeltable](https://pixeltable.com)**"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0LJoS2xlrJ1w"
      },
      "source": [
        "# LLM Setup\n",
        "\n",
        "This section initializes the OpenAI API key required for LLM used in the context engineering demo. The code securely handles API key management."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "dZ1C4Z42gcZL"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import getpass\n",
        "# Check if the OPENAI_API_KEY environment variable is set\n",
        "if 'OPENAI_API_KEY' not in os.environ:\n",
        "    # If not set, prompt the user to enter their securely\n",
        "    os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Oi93qimxrOxp"
      },
      "source": [
        "# Core Libraries:\n",
        "- **[pixeltable](https://docs.pixeltable.com)**: The main framework for managing multimodal data and AI workflows\n",
        "- **[pixelagent](https://github.com/pixeltable/pixelagent)**: Agent framework for building AI assistants with tool capabilities"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "22Ts6XLRrU2A"
      },
      "source": [
        "# RAG - Document Search\n",
        "\n",
        "This section demonstrates **Retrieval Augmented Generation (RAG)**, a powerful technique that combines the generative capabilities of large language models with external knowledge retrieval."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 68,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "NUDAUaJlgcZQ",
        "metadata": {},
        "outputId": "1564d37e-3fa6-42e6-97b3-e12384a460df"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Created directory 'context_engineering'.\n",
            "Created table 'documents'.\n"
          ]
        }
      ],
      "source": [
        "import pixeltable as pxt\n",
        "from pixeltable.iterators import DocumentSplitter\n",
        "from pixeltable.functions.huggingface import sentence_transformer\n",
        "\n",
        "# Drop the existing directory and create a new one for context engineering\n",
        "pxt.drop_dir(\"context_engineering\", if_not_exists=\"ignore\", force=True)\n",
        "pxt.create_dir(\"context_engineering\")\n",
        "\n",
        "# Create a Pixeltable table named \"documents\" with a Document column for PDFs\n",
        "documents_t = pxt.create_table(\n",
        "    \"context_engineering.documents\",\n",
        "    {\"pdf\": pxt.Document}\n",
        ")\n",
        "# Create a Pixeltable view named \"document_chunks\" from the \"documents\" table\n",
        "# Use DocumentSplitter to break down documents into chunks based on token limit\n",
        "documents_chunks = pxt.create_view(\n",
        "    \"context_engineering.document_chunks\",\n",
        "    documents_t,\n",
        "    iterator=DocumentSplitter.create(\n",
        "        document=documents_t.pdf,\n",
        "        separators=\"token_limit\",\n",
        "        limit=300\n",
        "    )\n",
        ")\n",
        "\n",
        "# Define the embedding model to be used for text embedding\n",
        "embed_model = sentence_transformer.using(model_id=\"intfloat/e5-large-v2\")\n",
        "# Add an embedding index to the \"text\" column of the document_chunks view using the defined embedding model\n",
        "documents_chunks.add_embedding_index(column=\"text\", string_embed=embed_model)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rAGEnf_6riG3"
      },
      "source": [
        "## Document Ingestion\n",
        "\n",
        "This section demonstrates the process of loading financial documents into our RAG system. The documents serve as the knowledge base that the AI agent will query to answer user questions."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 69,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "iJUQgzBb25oF",
        "outputId": "6c21e8d8-18d0-411d-f475-23244e7323b0"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Inserting rows into `documents`: 2 rows [00:00, 212.09 rows/s]\n",
            "Inserting rows into `document_chunks`: 34 rows [00:00, 552.73 rows/s]\n",
            "Inserted 36 rows with 0 errors.\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "36 rows inserted, 4 values computed."
            ]
          },
          "execution_count": 69,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Get existing Pixeltable tables for documents and document chunks\n",
        "documents_t = pxt.get_table(\"context_engineering.documents\")\n",
        "documents_chunks = pxt.get_table(\"context_engineering.document_chunks\")\n",
        "\n",
        "# Base URL for the documents\n",
        "DOCUMENT_URL = (\"https://github.com/pixeltable/pixeltable/raw/release/docs/resources/rag-demo/\")\n",
        "\n",
        "# List of document filenames\n",
        "document_urls = [\n",
        "    DOCUMENT_URL + doc for doc in [\n",
        "        \"Argus-Market-Digest-June-2024.pdf\",\n",
        "        \"Company-Research-Alphabet.pdf\",\n",
        "        # \"Zacks-Nvidia-Report.pdf\", # Commented out to exclude this document\n",
        "    ]\n",
        "]\n",
        "# Insert the document URLs into the documents table\n",
        "documents_t.insert({\"pdf\": url} for url in document_urls)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 70,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "CrM05Y93t4tl",
        "outputId": "bef53f82-cde4-4446-c571-1dc6ac65d28d"
      },
      "outputs": [
        {
          "data": {
            "text/html": [
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th>pos</th>\n",
              "      <th>text</th>\n",
              "      <th>pdf</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <td>19</td>\n",
              "      <td>other customers.\n",
              "However, clients and prospective clients should note that Argus Investors&#x27; Counsel and Argus Research Co., as units of The Argus\n",
              "Research Group, have certain employees in common, including those with both research and portfolio management responsibilities,\n",
              "and that Argus Research Co. employees participate in the management and marketing of the AIC core equity strategy and UIT and model\n",
              "portfolio products. Recipients of the Research reports in Singapore should contact the In ...... res Act, the Intermediary accepts legal responsibility for the contents of\n",
              "Research Reports in respect of such recipient in accordance with applicable law. When reports are distributed by Intermediaries in\n",
              "Singapore, the Intermediary, and not Argus Research, is solely responsible for ensuring that the recipients of the Research Reports\n",
              "understand the information contained in the Research Reports and that such information is suitable based on the customer&#x27;s profile and\n",
              "investment objectives.</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>18</td>\n",
              "      <td>this report constitutes\n",
              "individual investment, legal or tax advice. Argus may issue or may have issued other reports that are inconsistent with or may reach\n",
              "different conclusions than those represented in this report, and all opinions are reflective of judgments made on the original date of\n",
              "publication. Argus is under no obligation to ensure that other reports are brought to the attention of any recipient of this report. Argus\n",
              "shall accept no liability for any loss arising from the use of t ...... iates may serve as officers or directors of covered companies, or may own more than one percent of a covered company&#x27;s stock.\n",
              "Argus Investors&#x27; Counsel (AIC), a portfolio management business based in Stamford, Connecticut, is a customer of Argus Research Co.\n",
              "(ARC), based in New York.  Argus Investors&#x27; Counsel pays Argus Research Co. for research used in the management of the AIC core\n",
              "equity strategy and model portfolio and UIT products, and has the same access to Argus Research Co. reports as</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>17</td>\n",
              "      <td>is registered with the U.S. Securities and Exchange Commission. Argus Investors&#x27; Counsel is a subsidiary of The Argus Research Group,\n",
              "Inc. Neither The Argus Research Group nor any affiliate is a member of the FINRA or the SIPC. Argus Research is not a registered broker\n",
              "dealer and does not have investment banking operations. The Argus trademark, service mark and logo are the intellectual property of\n",
              "The Argus Research Group, Inc. The information contained in this research report is produced a ......  not an offer to sell or a solicitation of an offer to buy any security. The information and material presented\n",
              "in this report are for general information only and do not specifically address individual investment objectives, financial situations or\n",
              "the particular needs of any specific person who may receive this report. Investing in any security or investment strategies discussed may\n",
              "not be suitable for you and it is recommended that you consult an independent investment advisor. Nothing in</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>16</td>\n",
              "      <td>premium relative\n",
              "P/E in the 1.5- to 1.7-times range based on strong revenue and rising new orders, strong cash-growth trends, market-share gains,\n",
              "and increasing profitability. On all measures of historical comparable valuation, we calculate a value in the \\$340s, in a stable trend.\n",
              "Peer comparable analysis values Accenture in the \\$250s, in a slightly declining trend. Accenture trades at shrinking\n",
              "premiums to peers on P/E and price/book, and at a discount on price/sales; we believe that Accen ...... , in a stable trend and above current prices.\n",
              "Appreciation to our 12-month target price of \\$380 implies a risk-adjusted total return, including the 1.7% dividend yield,\n",
              "in excess of our forecast for S&amp;P 500 capital appreciation. On that basis, we are reiterating our BUY rating.\n",
              "On June 20, BUY-rated ACN closed at \\$306.16, up \\$20.81. (Jim Kelleher, CFA, 6/20/24)\n",
              "Argus Research Co. (ARC) is an independent investment research provider whose parent company, Argus Investors&#x27; Counsel, Inc. (AIC),</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>15</td>\n",
              "      <td>to entry, the consulting business can be quite competitive. Cognizant and IBM are leading competitors.\n",
              "McKinsey remains an industry force in consulting, while India-based firms such as Infosys compete in IT outsourcing. We believe\n",
              "that Accenture&#x27;s push into services such as digital, cloud and security give it a growth advantage over companies tied to legacy\n",
              "IT outsourcing, which has been hurt by the rapid switch to the cloud.\n",
              "COMPANY DESCRIPTION\n",
              "Based in Dublin, Ireland, Accenture is a glob ...... Resources.\n",
              "In FY23, approximately 47% of revenue was generated in the Americas, 33% in EMEA, and 20% in growth markets.\n",
              "MARKET DIGEST\n",
              "- 5 -\n",
              "VALUATION\n",
              "The ACN shares trade at 25.8-times our FY24 non-GAAP EPS estimate and at 23.65-times our FY25 projection. The\n",
              "two-year average forward P/E of 24.7 is now below the historical five-year (FY19-FY23) average of 27.3. The two-year average\n",
              "forward relative P/E of 1.07 is below the historical relative P/E of 1.42. We believe that Accenture warrants a</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>14</td>\n",
              "      <td>to retire in September 2024.\n",
              "We expect to see other leadership changes in fall 2024. Currently, John Walsh is COO; he previously served as chief\n",
              "strategic accounts &amp; global sales officer. Former COO Manish Sharma is group CEO of North America. Leo Framil is group CEO\n",
              "of Growth Markets, and Jean-Marc Ollagnier remains group CEO of Europe.  The company has a deep bench of talent and tends\n",
              "to promote from within, so we expect any leadership changes to be uneventful for Accenture.\n",
              "Under CEO Swe ...... or, which\n",
              "downsized in response to reduced tax receipts during the pandemic. However, Accenture expects government purchases of\n",
              "consulting services to be stable to higher in the coming quarters, as agencies invest in technology to keep costs low.\n",
              "The company&#x27;s strength in outsourcing, which generates more-consistent revenue, helps to temper this volatility.\n",
              "Accenture&#x27;s five operating groups also provide diversification during periods of weakness for any particular industry.\n",
              "With low barriers</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>13</td>\n",
              "      <td>of \\$8.7-\\$9.3 billion for FY24. For FY23, free cash flow was \\$9.0 billion. Free cash\n",
              "flow was \\$8.2 billion in FY22, \\$8.4 billion in FY21, and \\$7.6 billion in FY20.\n",
              "Accenture expects to return at least \\$7.7 billion to shareholders in FY24. Accenture returned \\$7.2 billion to shareholders\n",
              "in FY23; \\$6.1 billion to shareholders in FY22; \\$5.9 billion in FY21; \\$5.0 billion in FY20; and \\$4.6 billion in FY19.\n",
              "Beginning in FY20, Accenture switched from paying semiannual dividends to quarterly dividends. In September 2023,\n",
              "it announced a 15% hike its quarterly dividend to \\$1.29 per share. It previously raised its quarterly payout by 15% to \\$1.12 in\n",
              "September 2022, by 10% to \\$0.97 in November 2021, and by 10% to \\$0.88 in November 2020.\n",
              "Our dividend estimates are \\$5.16 per share for FY24 and \\$5.40 for FY25.\n",
              "MANAGEMENT &amp; RISKS\n",
              "Julie Sweet became CEO in September 2019, and at that time joined the board of directors; she has since become\n",
              "chairman. KC McClure has been CFO since 2019, and is now slated</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>12</td>\n",
              "      <td>.20; the new guidance implies growth of 2%-3% from FY23. That is down from 3%-5% growth\n",
              "guidance offered in March 2024.\n",
              "We are reducing our FY24 non-GAAP earnings estimate to \\$11.88 per diluted share from \\$12.11. However, we are\n",
              "raising our FY25 forecast to \\$12.70 per diluted share from \\$12.68. Our long-term annualized EPS growth rate forecast is 10%.\n",
              "FINANCIAL STRENGTH &amp; DIVIDEND\n",
              "Accenture&#x27;s financial strength ranking is High. The company, which formerly had fractional debt, had \\$1.68 billi ...... t as of the end of 3Q24. Moody&#x27;s long-term credit rating on Accenture is Aa3, and Standard &amp; Poor&#x27;s long-term rating is A+.\n",
              "Cash was \\$5.54 billion at the end of 3Q24. Cash was \\$9.05 billion at the end of FY23, \\$8.1 billion at the end of FY22,\n",
              "\\$8.42 billion at the end of FY21, and \\$8.5 billion at the end of FY20.\n",
              "Cash flow from operations was \\$9.52 billion in FY23, \\$9.54 billion in FY22, \\$8.98 billion in FY21, \\$8.36 billion in FY20,\n",
              "and \\$6.63 billion in FY19.\n",
              "Accenture forecast free cash flow</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>11</td>\n",
              "      <td>For all of FY23, Accenture generated record revenue of \\$64.1 billion, up 4% on a GAAP basis. Non-GAAP earnings\n",
              "rose 9% to \\$11.67 per diluted share.\n",
              "For fiscal 4Q24, Accenture guided for revenue of \\$16.05-\\$16.65 billion, which would be up 2% to 6% annually in local\n",
              "currency. Accenture assumes that currency translation will have a negative 2% impact in the current quarter, implying that revenue\n",
              "will be flat to up 4% on a GAAP basis for 4Q24.\n",
              "Management guided for FY24 revenue growth of 1.5%-2. ...... any is now assuming a 0.7% current headwind for FY24, after earlier guiding for a neutral currency impact for the\n",
              "full year. On that basis, Accenture is also guiding for 0.8%-1.8% GAAP revenue growth for FY24.\n",
              "MARKET DIGEST\n",
              "- 4 -\n",
              "Management is modeling 10 basis points of non-GAAP operating margin expansion, to 15.5%, compared with 15.4%\n",
              "for FY23. As a result of these changes and other line-item inputs, management now forecasts full-year non-GAAP EPS of \\$11.85-\n",
              "\\$12.00, reduced from \\$11.97-\\$12</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>10</td>\n",
              "      <td>(ended May 31, 2024), Accenture reported revenue of \\$16.47 billion, which was down 1% year over year\n",
              "on a reported basis and up 1% in local currency. Revenue was below \\$16.55 billion midpoint of management&#x27;s \\$16.25-\\$16.85\n",
              "billion guidance range and missed the \\$16.54 billion consensus forecast.\n",
              "The GAAP gross margin was 33.4% in 3Q24, compared to 30.9% in 2Q24 and 33.4% a year earlier. The GAAP operating\n",
              "margin was 16.0% in 3Q24, compared to 13.0% in 2Q24 and 14.2% a year earlier. Accenture took a \\$77 million charge for business\n",
              "reorganization in 3Q24 and a total \\$333 million charge for FY24 to date. Adjusted to exclude one-time charges, the non-GAAP\n",
              "operating margin was 16.4% in 3Q24, compared to 13.7% in 2Q24 and 16.4% a year earlier.\n",
              "On a non-GAAP basis, Accenture earned \\$3.13 per diluted share in fiscal 3Q24, down 2% year over year. Non-GAAP\n",
              "EPS missed the consensus forecast of \\$3.15. The company guides on annual EPS but not typically on quarterly EPS.</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>9</td>\n",
              "      <td>at North American communications and media customers.\n",
              "Products, the largest operating group at 30% of revenue, posted revenue of \\$4.98 billion; that represented sales of at least\n",
              "\\$4.5 billion for a ninth straight quarter. Product sales were up 2% in local currency. Financial services (18% of revenue) was down\n",
              "5% in local currency, as insurance, banking and capital markets are all impacted by weakened activity due to high interest rates.\n",
              "The Health &amp; Public Services category (21% of sales) g ......  experienced growth\n",
              "in seven of the 13 broad industry verticals that it serves. Accenture trimmed its already conservative FY24 profit outlook, but\n",
              "continues to model single-digit sales and EPS growth for FY24. The outlook reflects ongoing macroeconomic pressures, but also\n",
              "suggests growth in targeted areas, disciplined cost management, share gains at the expense of smaller rivals, and momentum in\n",
              "the very early days of the generative AI opportunity.\n",
              "EARNINGS &amp; GROWTH ANALYSIS\n",
              "For fiscal 3Q24</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>8</td>\n",
              "      <td>Capital Markets. North American operating profit rose 2% year over year on an adjusted\n",
              "basis (excluding business reorganization costs).\n",
              "Formerly Europe-only regional sales now include Middle East &amp; Africa, and this region is now called EMEA. On a\n",
              "restated basis for all periods, EMEA sales (35% of revenue) decreased 1% in local currency and grew 3% on a GAAP basis. EMEA\n",
              "saw growth in Public Services, and was offset by weakness in CMT and in Banking &amp; Capital Markets. Strength in Italy offset ...... cturing Americas operations, a significant portion of\n",
              "restructuring in FY24 is in overseas markets. Excluding restructuring costs, operating income rose 3% in EMEA and fell 9% in\n",
              "growth markets during fiscal 3Q24.\n",
              "For the company&#x27;s operating groups, Communications, Media, &amp; Technology (17% of revenue) was down 4% in GAAP\n",
              "and down 1% in constant currency. CMT continues to be hurt by the softness in deals with smaller customers, particularly in\n",
              "software &amp; platforms, and by corporate downsizing</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>7</td>\n",
              "      <td>28 billion (44% of total) rose 4% from the prior year, and were down 12%\n",
              "sequentially. Given consulting revenue of \\$8.46 billion (51% of total), consulting book-to-bill was 1.10. Managed Services\n",
              "(formerly Outsourcing) bookings were \\$11.78 billion, up 42% annually and 7% sequentially. Outsourcing revenue was \\$8.01\n",
              "billion (49% of total), up 2% in GAAP and 4% in local currency. Outsourcing book-to-bill was 1.47, exceeding 1.4 for a second\n",
              "consecutive quarter.\n",
              "MARKET DIGEST\n",
              "- 3 -\n",
              "Accenture loo ...... e-digit growth, while Operations was about flat in local currency. Strategy &amp; Consulting has been impacted in recent\n",
              "quarters by weakness in small enterprise contracts, so its recovery in the quarter is a positive sign.\n",
              "On a regional basis, fiscal 3Q24 North American revenue of \\$7.83 billion (48% of total) was up 1% in local currency\n",
              "and on a GAAP basis. North American constant-currency results reflected strength in Public Service &amp; Health, partly offset by\n",
              "weaker trends in CMT and Banking &amp;</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>6</td>\n",
              "      <td>both niche capabilities and geographic breadth. Accenture has conducted 35 acquisitions for \\$5.2 billion in FY24 YTD; that\n",
              "compares with \\$2.5 billion spent on acquisitions for all of FY23.\n",
              "Clients need to be far along the path to digital transformation before implementing Gen AI, and that is acting as a gating\n",
              "factor on full realization of this opportunity. The need for clients to be digitally ready in order to embrace generative AI fully is\n",
              "both a challenge and an opportunity, according to  ...... th digital categories. In our view, Accenture has the global scale,\n",
              "industry expertise, and deep experience to help companies on their path to digitization.\n",
              "In a positive sign for future business, bookings in 3Q24 extended strength from 1H24 following a soft second-half FY23\n",
              "trend. For 3Q24, bookings of \\$21.1 billion increased 22% year over year in GAAP and 26% in local currency. Based on revenue\n",
              "of \\$16.6 billion, the total book-to-bill for 3Q24 was 1.28.\n",
              "For 3Q24, consulting bookings of \\$9.</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>5</td>\n",
              "      <td>The company has moved quickly to adjust to lower levels of discretionary spending on smaller\n",
              "projects. The business environment is somewhat better in the Managed Services space (formerly Outsourcing). Accenture\n",
              "recorded 23 deals with total value exceeding \\$100 million in fiscal 3Q24, bring the year-to-date total of such deals to 92 — which\n",
              "was seven more than were recorded as of the same point in FY23. This money will &quot;layer in&quot; in FY25, helping offset the weaker\n",
              "current environment.\n",
              "Most n ...... centure also has had over \\$500 million in year to date Gen AI revenue as this opportunity\n",
              "has been fast to monetize.\n",
              "Customers are in the early phases of their AI journeys, and Accenture currently is mainly seeing smaller and tentative\n",
              "investments from clients. Every client is investing in this area, however, and from smaller projects clients &quot;are headed toward\n",
              "larger projects.&quot; One way Accenture is scaling up rapidly for this opportunity is inorganic growth via acquisition, which is adding</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>4</td>\n",
              "      <td>36% in 2022, versus a 30% decline for peers; advanced 59% in 2021, versus 35% for peers; and rose 24% in 2020, while peers\n",
              "were up 9%.\n",
              "For fiscal 3Q24 (ended May 31, 2024), Accenture reported revenue of \\$16.47 billion, which was down 1% year over year\n",
              "on a reported basis and up 1% in local currency. Revenue was below \\$16.55 billion midpoint of management&#x27;s \\$16.25-\\$16.85\n",
              "billion guidance range and missed the \\$16.54 billion consensus forecast. On a non-GAAP basis, Accenture earned \\$3.13 per\n",
              "di ...... s not materialized as the company initially anticipated at the beginning to the year,\n",
              "due to inflation and high interest rates have led to caution in discretionary spending. The consulting business, exposed to highly\n",
              "discretionary and shorter-term projects that are mainly small to mid-sized in scope, has been particularly impacted by these trends.\n",
              "The CEO stated that Accenture has responded to the challenging environment with &quot;resilience and agility&quot; while\n",
              "remaining laser focused on clients.</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>3</td>\n",
              "      <td>ure is investing\n",
              "inorganically to expand its AI and other capabilities; the company&#x27;s 35 niche acquisitions in FY24 to date are more than in all of\n",
              "FY23.\n",
              "&#x27;34\n",
              "&#x27;39\n",
              "&#x27;44\n",
              "&#x27;49\n",
              "&#x27;54\n",
              "&#x27;59\n",
              "&#x27;64\n",
              "&#x27;69\n",
              "&#x27;74\n",
              "&#x27;79\n",
              "&#x27;84\n",
              "&#x27;89\n",
              "&#x27;94\n",
              "&#x27;99\n",
              "&#x27;04\n",
              "&#x27;09\n",
              "&#x27;14\n",
              "&#x27;19\n",
              "2023 - DJIA: \n",
              "37,689.54\n",
              "1934 - DJIA: 104.04\n",
              "MARKET DIGEST\n",
              "- 2 -\n",
              "In our view, Accenture has the size, scale, global reach, and broad industry expertise to continue growing faster than the\n",
              "industry and taking share from competitors. Accenture&#x27;s share price, which rose in  ...... 24 with the consulting market. From a valuation perspective, Accenture appears attractive based on our\n",
              "discounted free cash flow model and blended valuation analysis. We are reiterating our BUY rating and our 12-month target price\n",
              "of \\$380.\n",
              "RECENT DEVELOPMENTS\n",
              "Accenture is down 11% year-to-date in 2024, versus a 21% gain for peers. Accenture rose 32% in 2023, versus a 40%\n",
              "gain for the peer group of information processing and computing &amp; storage companies in Argus coverage. Accenture declined</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>2</td>\n",
              "      <td>ly on June 20, despite the company reporting fiscal 3Q24\n",
              "revenue and non-GAAP EPS that missed consensus forecasts. Both GAAP revenue and adjusted EPS edged lower year over year.\n",
              "On a constant currency basis, the consulting and IT outsourcing leader posted 1% growth in revenue year over year, while adjusted\n",
              "earnings declined 2% for fiscal 3Q24.\n",
              "While the demand environment remains soft in the small-project consulting space, the overall consulting business also\n",
              "returned to growth in 3Q24. Acce ...... y has achieved \\$500 million in AI revenue in FY24 to date.\n",
              "Generative AI is the fastest-growing technology opportunity in company history.\n",
              "CEO Julie Sweet noted that most customers are just getting started on their AI journeys, creating a strong runway for\n",
              "future growth. Clients need to be &quot;far along the path&quot; to digital transformation before implementing Gen AI. While that is acting\n",
              "as a gating factor on full realization of this opportunity, momentum is plainly building with clients. Accent</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>1</td>\n",
              "      <td>500 lower by 0.79% and 0.25%,\n",
              "respectively. In a rare event, shares of Nvidia not only lost ground, but lost a relatively meaningful amount (3.5%), proving nothing\n",
              "can go up forever. Still, the major indices are comfortably ahead for the year to date — and the big non-AI mover for stocks is\n",
              "the future direction of interest rates, which remains a concern for Wall Street and (for one day at least) offset AI mania.\n",
              "ACCENTURE PLC (NYSE: ACN, \\$306.16) BUY\n",
              "ACN: Shares rally on AI optimism\n",
              "*\n",
              "Accen ...... entum for the business.\n",
              "*\n",
              "Total bookings were strong in 3Q24, rising 22% annually on acceleration in managed services and resulting in a\n",
              "1.3 book-to-bill. Accenture still appears to be taking share from competitors.\n",
              "*\n",
              "We believe that Accenture has the financial resources, customer presence, and market strength to thrive as\n",
              "companies accelerate the process of digital transformation and begin their AI journeys.\n",
              "ANALYSIS\n",
              "INVESTMENT THESIS\n",
              "Shares of BUY-rated Accenture plc (NYSE: ACN) rose solid</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>0</td>\n",
              "      <td>MARKET DIGEST\n",
              "- 1 -\n",
              " FRIDAY, JUNE 21, 2024\n",
              "JUNE 20, DJIA: 39,134.76\n",
              "UP 299.90\n",
              "Independent Equity Research Since 1934\n",
              "ARGUS\n",
              "A R G U S  R E S E A R C H  C O M P A N Y  •  6 1  B R O A D W A Y  •  N E W  Y O R K ,  N. Y.  1 0 0 0 6  •  ( 2 1 2 )  4 2 5  -  7 5 0 0\n",
              "LONDON SALES &amp; MARKETING OFFICE TEL 011-44-207-256-8383 / FAX 011-44-207-256-8363\n",
              "®\n",
              "Good Morning. This is the Market Digest for Friday, June 21, 2024, with analysis of the financial markets and comments on\n",
              "Accenture plc.\n",
              "IN THIS ISSUE:\n",
              "*\n",
              "Growth Stock: Accenture plc: Shares rally on AI optimism (Jim Kelleher)\n",
              "MARKET REVIEW:\n",
              "Yogi Berra famously said &quot;When you come to a fork in the road, take it.&quot; Stock investors did just that on Thursday,\n",
              "pushing the Dow Jones Industrial Average higher by 0.77% but the Nasdaq Composite and S&amp;P</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_00d7085b9c73b1f11214aa67f7135fab30684e165d763128ecbdcfa1db95efcf.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>13</td>\n",
              "      <td>subject\n",
              "to change without notice and Fidelity does not guarantee their accuracy, timeliness, completeness or usefulness, and is not responsible or liable for any content, advertising, products, or\n",
              "other materials on or available from third parties nor is Fidelity liable for losses resulting from their use. You use Third-Party Content only at your own risk. With respect to research\n",
              "reports, in order to comply with applicable laws and regulations, Fidelity may at times suppress the delivery o ...... \n",
              "solicitation of an offer to buy, or a recommendation for any security by Fidelity or any Third-Party Provider. Requests for reports are unsolicited. Individuals are responsible for determining\n",
              "whether any investment, security or strategy is appropriate or suitable and that neither Fidelity nor any Third-Party Provider has made any determination that any recommendation,\n",
              "investment, or strategy in any content is suitable or appropriate based on investment objectives and financial situations.</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_a3b5f048384678987f216fbaa7ebeace9a9a89e117fd364f4ab50b677456f9d3.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>12</td>\n",
              "      <td>2024:\n",
              "\\$176.30\n",
              "Communication Services Sector\n",
              "Market Capitalization:\n",
              "\\$2182.8 B\n",
              "Interactive Media &amp; Services Industry\n",
              "Alphabet Class A\n",
              "The content on this page is provided by third parties and not Fidelity. Fidelity did not prepare and does not endorse such content. All are third-party companies that are not affiliated with Fidelity.\n",
              "See each section in this report for third-party content attribution.\n",
              " \n",
              " © 2024 FMR LLC. All rights reserved. 447628.8.0\n",
              "Page 4\n",
              "Report created on June 21, 2024\n",
              "Impo ...... alyst recommendations data and analysis provided by Investars. All are third-party companies that are not affiliated with Fidelity.\n",
              "This report provides quotes and data concerning the financial markets, securities and other subjects. Content is supplied by companies that are not affiliated with Fidelity (&quot;Third-Party\n",
              "Content&quot;). Most Third-Party Content and its source are clearly and prominently identified. Fidelity does not prepare, edit, or endorse Third-Party Content. News and research are</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_a3b5f048384678987f216fbaa7ebeace9a9a89e117fd364f4ab50b677456f9d3.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>11</td>\n",
              "      <td>. equity securities in each industry to which a company belongs, as\n",
              "determined by Standard &amp; Poor&#x27;s. S&amp;P uses the Global Industry Classification Standard (GICS)SM, an industry classification system developed by S&amp;P in\n",
              "collaboration with Morgan Stanley Capital International (MSCI).\n",
              "A company is assigned to a single GICS sub-industry according to the definition of its principal business activity as determined by Standard &amp; Poor&#x27;s and MSCI.\n",
              "Revenues are a significant factor in defining principa ......  not the best for items such as Debt to Capital Ratio where a lower number means less debt. Therefore, being\n",
              "in the 1st percentile indicates lower debt than its peers in the industry.\n",
              "The Industry Average is a market cap-weighted average of the non-null values in the industry.\n",
              "Company Research Highlights\n",
              "®\n",
              "GOOGL\n",
              "NASDAQ\n",
              "This is not an investment recommendation from Fidelity Investments. The information\n",
              "contained in this report is sourced from independent, third party providers.\n",
              "Price on 6/20/</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_a3b5f048384678987f216fbaa7ebeace9a9a89e117fd364f4ab50b677456f9d3.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>10</td>\n",
              "      <td>.4\n",
              "1.5\n",
              "--\n",
              "Enterprise Value\n",
              "\\$0.00\n",
              "\\$0.00\n",
              "--\n",
              "Price / Sales\n",
              "6.9\n",
              "7.6\n",
              "--\n",
              "Price / Book\n",
              "7.9\n",
              "8.8\n",
              "--\n",
              "Price / Cash Flow\n",
              "23.3\n",
              "24.5\n",
              "--\n",
              "0: Worst\n",
              "Best: 100\n",
              "Company Quality Ratios\n",
              "GOOGL\n",
              "Industry\n",
              "GOOGL Percentile Rank in Industry\n",
              "Gross Profit Margin (Trailing 12 Months)\n",
              "61.0%\n",
              "71.4\n",
              "--\n",
              "Operating Margin (Trailing 12 Months)\n",
              "29.3%\n",
              "31.7\n",
              "--\n",
              "Return on Assets (Trailing 12 Months)\n",
              "20.7%\n",
              "19.7\n",
              "--\n",
              "Return on Equity (Trailing 12 Months)\n",
              "29.5%\n",
              "26.0\n",
              "--\n",
              "0: Worst\n",
              "Best: 100\n",
              "Growth Rates (%)\n",
              "GOOGL\n",
              "Industry\n",
              "GOOGL Percentile Rank in Industry\n",
              "Revenue Growth (Trailing 12 Months vs. Prior Trailing 12 Months)\n",
              "+11.8%\n",
              "+15.1\n",
              "--\n",
              "EPS Growth (Trailing 12 Months vs. Prior Trailing 12 Months)\n",
              "+45.2%\n",
              "+71.2\n",
              "--\n",
              "Revenue % Change (Trailing 12 Months)\n",
              "+15.41%\n",
              "+19.27\n",
              "--\n",
              "0: Worst\n",
              "Best: 100\n",
              "** The Industry Average and Percentile Rank methodology is based on the daily list of U.S</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_a3b5f048384678987f216fbaa7ebeace9a9a89e117fd364f4ab50b677456f9d3.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>9</td>\n",
              "      <td>/B/E/S from Refinitiv\n",
              "Earnings in US Dollars\n",
              "ACTUALS\n",
              "ESTIMATES\n",
              "STARMINE ESTIMATES\n",
              "GOOGL PRICE\n",
              "Q2\n",
              "Q1\n",
              "2024\n",
              "2024\n",
              "2024\n",
              "2024\n",
              "Q4\n",
              "Q3\n",
              "Q2\n",
              "Q1\n",
              "2023\n",
              "2023\n",
              "2023\n",
              "2023\n",
              "Q4\n",
              "Q3\n",
              "Q2\n",
              "Q1\n",
              "2022\n",
              "2022\n",
              "2022\n",
              "2022\n",
              "\\$0\n",
              "\\$100\n",
              "\\$200\n",
              "Today\n",
              "1.23\n",
              "1.21\n",
              "1.06\n",
              "1.05\n",
              "1.17\n",
              "1.44\n",
              "1.55\n",
              "1.64\n",
              "1.89\n",
              "1.84\n",
              "Actuals vs. Estimates for Fiscal Year\n",
              "First Call Estimates\n",
              " \n",
              "Actual (\\$)\n",
              "Consensus (\\$)\n",
              "Analysts in Consensus\n",
              "Low / High Range (\\$)\n",
              "Previous Year (Ends 12/31/23)\n",
              "5.80\n",
              "5.74\n",
              "48\n",
              "5.26 / 6.10\n",
              "Next Year (Ends 12/31/24)\n",
              "--\n",
              "7.57\n",
              "53\n",
              "6.87 / 8.17\n",
              "Industry Comparisons**  Data provided by S&amp;P Compustat\n",
              "Valuation Ratios (trailing 12 months)\n",
              "GOOGL\n",
              "Industry\n",
              "GOOGL Percentile Rank in Industry\n",
              "Price / Earnings\n",
              "27.0\n",
              "28.1\n",
              "--\n",
              "PEG Ratio\n",
              "1</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_a3b5f048384678987f216fbaa7ebeace9a9a89e117fd364f4ab50b677456f9d3.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>8</td>\n",
              "      <td>(PDF).\n",
              "Company Research Highlights\n",
              "®\n",
              "GOOGL\n",
              "NASDAQ\n",
              "This is not an investment recommendation from Fidelity Investments. The information\n",
              "contained in this report is sourced from independent, third party providers.\n",
              "Price on 6/20/2024:\n",
              "\\$176.30\n",
              "Communication Services Sector\n",
              "Market Capitalization:\n",
              "\\$2182.8 B\n",
              "Interactive Media &amp; Services Industry\n",
              "Alphabet Class A\n",
              "The content on this page is provided by third parties and not Fidelity. Fidelity did not prepare and does not endorse such content. All ar ...... 04/25/24\n",
              "Reported Earnings: \\$1.89 per share\n",
              "Next Expected Report Date: 07/23/24\n",
              "GOOGL exceeded the First Call Consensus\n",
              "of \\$1.515 and exceeded the StarMine\n",
              "SmartEstimate from Refinitiv of \\$1.533 for\n",
              "Q1 2024.\n",
              "About Starmine SmartEstimate\n",
              "The StarMine SmartEstimate from Refinitiv\n",
              "seeks to be more accurate than the\n",
              "consensus EPS by calculating an analyst&#x27;s\n",
              "accuracy and timeliness of an analyst&#x27;s\n",
              "estimates into its estimate of earnings.\n",
              "Actuals vs. Estimates by Fiscal Quarter  Data provided by I</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_a3b5f048384678987f216fbaa7ebeace9a9a89e117fd364f4ab50b677456f9d3.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>7</td>\n",
              "      <td>i) after the Firm Name indicates an\n",
              "independent firm that derives no\n",
              "financial benefit from the nature of their\n",
              "recommendations.\n",
              "2. StarMine from Refinitiv Relative Accuracy\n",
              "is based on a statistical aggregation of\n",
              "how well a firm performed on all of its\n",
              "individual stock recommendations in a\n",
              "given sector. StarMine from Refinitiv first\n",
              "calculates the individual scores for each\n",
              "set of recommendations for a single\n",
              "stock over a 24 month period. Then\n",
              "StarMine from Refinitiv rolls up these\n",
              "individ ......  between the Equity Summary\n",
              "Score analyst count and the number of\n",
              "underlying analysts listed. Due to the\n",
              "timing in receiving ratings changes into\n",
              "the Equity Summary Score model, the\n",
              "Equity Summary Score analyst count\n",
              "may lag the ratings count displayed by\n",
              "one or more days. There may also be\n",
              "analyst count variations for symbols with\n",
              "multiple share classes and ADRs. More\n",
              "details on Equity Summary Score\n",
              "calculation are included in the\n",
              "Understanding and Using the Equity\n",
              "Summary Score Methodology</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_a3b5f048384678987f216fbaa7ebeace9a9a89e117fd364f4ab50b677456f9d3.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>6</td>\n",
              "      <td>04/25/24\n",
              "Overweight\n",
              "Truist Securities, Inc\n",
              "Buy\n",
              " \n",
              "16.59%\n",
              "04/25/24\n",
              "Buy\n",
              "Argus Analyst\n",
              "Buy\n",
              " \n",
              "45.59%\n",
              "04/30/24\n",
              "Buy\n",
              "Canaccord Capital\n",
              "Buy\n",
              " \n",
              "28.12%\n",
              "04/25/24\n",
              "Buy\n",
              "JMP Securities\n",
              "Outperform\n",
              " \n",
              "76.44%\n",
              "05/22/24\n",
              "Market Outperform\n",
              "Refinitiv/Verus (i)\n",
              "Neutral\n",
              " \n",
              "-17.37%\n",
              "06/17/24\n",
              "Hold\n",
              "Zacks Investment Research, Inc (i)\n",
              "Outperform\n",
              " \n",
              "8.06%\n",
              "06/15/24\n",
              "Outperform\n",
              "ISS-EVA (i)\n",
              "Underperform\n",
              " \n",
              "0.55%\n",
              "06/01/24\n",
              "Underweight\n",
              "Jefferson Research (i)\n",
              "Buy\n",
              " \n",
              "0.10%\n",
              "06/13/24\n",
              "Buy\n",
              "Trading Central (i)\n",
              "Neutral\n",
              " \n",
              "-24.10%\n",
              "06/16/24\n",
              "Neutral\n",
              "McLean Capital Management (i)\n",
              "Buy\n",
              " \n",
              "39.15%\n",
              "06/17/24\n",
              "Buy\n",
              "Argus Research A6/Quantitative (i)\n",
              "Neutral\n",
              " \n",
              "19.07%\n",
              "06/19/24\n",
              "Hold\n",
              "I/B/E/S Estimates from Refinitiv\n",
              "--\n",
              " \n",
              "--\n",
              "06/20/24\n",
              "Buy\n",
              "Equity Summary Score (7 Firms†)\n",
              "--\n",
              " \n",
              "--\n",
              "06/21/24\n",
              "Bullish\n",
              "• Opinion used in Equity Summary Score\n",
              "1. (</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_a3b5f048384678987f216fbaa7ebeace9a9a89e117fd364f4ab50b677456f9d3.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>5</td>\n",
              "      <td>KeyBanc Capital Markets\n",
              "Buy\n",
              " \n",
              "0.74%\n",
              "05/14/24\n",
              "Buy\n",
              "Needham\n",
              "Buy\n",
              " \n",
              "-0.71%\n",
              "10/25/23\n",
              "Buy\n",
              "Bernstein\n",
              "Neutral\n",
              " \n",
              "25.77%\n",
              "04/25/24\n",
              "Market Perform\n",
              "Stifel Nicolaus\n",
              "Buy\n",
              " \n",
              "107.44%\n",
              "05/15/24\n",
              "Buy\n",
              "Jefferies\n",
              "Buy\n",
              " \n",
              "26.21%\n",
              "06/06/24\n",
              "Buy\n",
              "CSFB\n",
              "Outperform\n",
              " \n",
              "5.22%\n",
              "07/26/23\n",
              "Outperform\n",
              "Merrill Lynch\n",
              "Buy\n",
              " \n",
              "13.70%\n",
              "06/11/24\n",
              "Buy\n",
              "Wells Fargo Securities\n",
              "Neutral\n",
              " \n",
              "8.98%\n",
              "04/26/24\n",
              "Market Perform\n",
              "Roth Capital Partners\n",
              "Buy\n",
              " \n",
              "50.37%\n",
              "04/26/24\n",
              "Buy\n",
              "UBS\n",
              "Neutral\n",
              " \n",
              "17.86%\n",
              "05/20/24\n",
              "Neutral\n",
              "Morgan Stanley\n",
              "Outperform\n",
              " \n",
              "20.55%\n",
              "06/11/24\n",
              "Overweight (o)\n",
              "Wedbush Morgan\n",
              "Buy\n",
              " \n",
              "44.38%\n",
              "04/25/24\n",
              "Outperform\n",
              "Citigroup Investment Research\n",
              "Buy\n",
              " \n",
              "14.75%\n",
              "05/15/24\n",
              "Buy\n",
              "Baird\n",
              "Outperform\n",
              " \n",
              "57.30%\n",
              "04/26/24\n",
              "Outperform\n",
              "Deutsche Bank\n",
              "Buy\n",
              " \n",
              "14.32%\n",
              "07/24/23\n",
              "Buy\n",
              "Piper Jaffray\n",
              "Outperform\n",
              " \n",
              "19.55%</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_a3b5f048384678987f216fbaa7ebeace9a9a89e117fd364f4ab50b677456f9d3.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>4</td>\n",
              "      <td>Provided by StarMine from Refinitiv as of 6/21/2024\n",
              "Firm1\n",
              "Starmine\n",
              "Relative Accuracy2 Standardized Opinion3\n",
              "Refinitiv/Verus (i)\n",
              "30\n",
              "Neutral\n",
              "Zacks Investment Research, Inc (i)\n",
              "56\n",
              "Outperform\n",
              "ISS-EVA (i)\n",
              "86\n",
              "Underperform\n",
              "Jefferson Research (i)\n",
              "34\n",
              "Buy\n",
              "Trading Central (i)\n",
              "10\n",
              "Neutral\n",
              "McLean Capital Management (i)\n",
              "46\n",
              "Buy\n",
              "Argus Research A6/Quantitative (i)\n",
              "72\n",
              "Neutral\n",
              "• Opinion used in Equity Summary Score\n",
              "GOOGL Equity Summary Score\n",
              "7 Firms†\n",
              "10\n",
              "9\n",
              "VERY BULLISH\n",
              "7\n",
              "BULLISH\n",
              "3\n",
              "NEUTRAL\n",
              "1\n",
              "BEARISH\n",
              "0\n",
              "VERY BEARISH\n",
              "7.7\n",
              "Bullish\n",
              "Firm Opinions  Provided by Investars as of 6/21/2024\n",
              "STANDARDIZED OPINION\n",
              "CURRENT FIRM OPINION\n",
              "Firm1 / Aggregate Opinion\n",
              "Opinion\n",
              "1 Year History\n",
              "Investars\n",
              "Smartindex\n",
              "Date\n",
              "Opinion\n",
              "Oppenheimer &amp; Company\n",
              "Outperform\n",
              " \n",
              "29.14%\n",
              "04/26/24\n",
              "Outperform\n",
              "RBC Capital Markets\n",
              "Outperform\n",
              " \n",
              "15.92%\n",
              "06/05/24\n",
              "Outperform\n",
              "Raymond James\n",
              "Outperform\n",
              " \n",
              "12.10%\n",
              "12/20/23\n",
              "Outperform</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_a3b5f048384678987f216fbaa7ebeace9a9a89e117fd364f4ab50b677456f9d3.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>3</td>\n",
              "      <td>on 6/20/2024:\n",
              "\\$176.30\n",
              "Communication Services Sector\n",
              "Market Capitalization:\n",
              "\\$2182.8 B\n",
              "Interactive Media &amp; Services Industry\n",
              "Alphabet Class A\n",
              "The content on this page is provided by third parties and not Fidelity. Fidelity did not prepare and does not endorse such content. All are third-party companies that are not affiliated with Fidelity.\n",
              "See each section in this report for third-party content attribution and see page 4 for full disclosures.\n",
              "Page 2\n",
              "Report created on June 21, 2024\n",
              "Equity Sum ...... rom\n",
              "contributors. The number of contributors for\n",
              "each security where there is a consensus\n",
              "recommendation is provided. Each\n",
              "contributor determines how their individual\n",
              "recommendation scale maps to the I/B/E/S\n",
              "from Refinitiv 5-point scale.\n",
              "Visit Fidelity.com for firm descriptions,\n",
              "detailed methodologies, and more\n",
              "information on the Equity Summary Score,\n",
              "First Call Consensus, opinion history and\n",
              "performance, and most current available\n",
              "research reports for GOOGL.\n",
              "Equity Summary Score  (7 Firms†)</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_a3b5f048384678987f216fbaa7ebeace9a9a89e117fd364f4ab50b677456f9d3.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>2</td>\n",
              "      <td>6.0\n",
              "   200-Day Average\n",
              "22.6\n",
              "Price Performance (% Change)\n",
              "   4 Week\n",
              "1.6\n",
              "   13 Week\n",
              "19.4\n",
              "   52 Week\n",
              "43.2\n",
              "1 Year Annualized as of 6/20/2024\n",
              "   Total Return\n",
              "+186.32%\n",
              "   Standard Deviation\n",
              "0.29\n",
              "   Beta\n",
              "1.23\n",
              "Volume\n",
              "   Average 10-Day\n",
              "21,672,224.2\n",
              "   Average 90-Day\n",
              "28,560,513.5\n",
              "Shares Outstanding\n",
              "6,741,000,000\n",
              "Environmental, Social &amp; Governance Summary (ESG)\n",
              "Environmental, Social &amp; Governance Summary (ESG)\n",
              "PROVIDED BY MSCI\n",
              "RATING\n",
              "GOOGL\n",
              "INDUSTRY\n",
              "Overall\n",
              "AVERAGE\n",
              "AVERAGE\n",
              "AVERAGE\n",
              "AVERAGE\n",
              "   Environment\n",
              "LEADER\n",
              "LEADER\n",
              "LEADER\n",
              "LEADER\n",
              "   Social\n",
              "AVERAGE\n",
              "AVERAGE\n",
              "AVERAGE\n",
              "AVERAGE\n",
              "   Governance\n",
              "LAGGARD\n",
              "LAGGARD\n",
              "LAGGARD\n",
              "LAGGARD\n",
              "TRBC Industry: IT Services / Consulting\n",
              "Risk:\n",
              "Leader = Top 25%\n",
              "Average = Middle 50%\n",
              "Laggard = Bottom 25%\n",
              "Company Research Highlights\n",
              "®\n",
              "GOOGL\n",
              "NASDAQ\n",
              "This is not an investment recommendation from Fidelity Investments. The information\n",
              "contained in this report is sourced from independent, third party providers.\n",
              "Price</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_a3b5f048384678987f216fbaa7ebeace9a9a89e117fd364f4ab50b677456f9d3.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>1</td>\n",
              "      <td>+11.78%\n",
              "Enterprise Value\n",
              "\\$2103.1 B\n",
              "6/20/2024\n",
              "Ex. Dividend Date\n",
              "6/10/2024\n",
              "Dividend\n",
              "\\$0.200000\n",
              "Dividend Yield (Annualized)\n",
              "0.45%\n",
              "6/20/2024\n",
              "P/E (TTM)\n",
              "27.0\n",
              "6/20/2024\n",
              "Earning Yield (TTM)\n",
              "+3.70%\n",
              "6/20/2024\n",
              "EPS (Adjusted TTM)\n",
              "\\$1.89\n",
              "4/25/2024\n",
              "Consensus EPS Estimate\n",
              "(Q2 2024)\n",
              "\\$1.84\n",
              "EPS Growth\n",
              "(TTM vs. Prior TTM)\n",
              "+45.2%\n",
              "3-Year Price Performance  Data provided by DataScope from Refinitiv\n",
              "Q3\n",
              "Q4\n",
              "Q1\n",
              "Q2\n",
              "Q3\n",
              "Q4\n",
              "Q1\n",
              "Q2\n",
              "Q3\n",
              "Q4\n",
              "Q1\n",
              "Q2\n",
              "2021\n",
              "2022\n",
              "2023\n",
              "2024\n",
              "-40%\n",
              "-20%\n",
              "0%\n",
              "20%\n",
              "40%\n",
              "0\n",
              "500\n",
              "Average Monthly Volume (Millions)\n",
              "50-Day Moving Average\n",
              "200-Day Moving Average\n",
              "Trading Characteristics\n",
              "52 Week High\n",
              "6/12/2024\n",
              "\\$180.41\n",
              "52 Week Low\n",
              "7/11/2023\n",
              "\\$115.35\n",
              "% Price Above/Below\n",
              "   20-Day Average\n",
              "2.4\n",
              "   50-Day Average</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_a3b5f048384678987f216fbaa7ebeace9a9a89e117fd364f4ab50b677456f9d3.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>0</td>\n",
              "      <td>Company Research Highlights\n",
              "®\n",
              "Report created on June 21, 2024\n",
              "This is not an investment recommendation from Fidelity Investments. Fidelity provides this information as a service to investors from independent, third-party sources.\n",
              "Performance of analyst recommendations are provided by StarMine from Refinitiv. Current analyst recommendations are collected and standardized by Investars.\n",
              "See each section in this report for third-party content attribution, as well as the final page of the report  ...... Market Capitalization:\n",
              "\\$2182.8 B\n",
              "Interactive Media &amp; Services Industry\n",
              "Business Description  Data provided by S&amp;P Compustat\n",
              "Alphabet Inc. offers various products and platforms in the United States, Europe, the Middle\n",
              "East, Africa, the Asia-Pacific, Canada, and Latin America. It operates through Google Services,\n",
              "Google Cloud, and Other Bets segments.\n",
              "Key Statistics\n",
              "Employee Count\n",
              "182,502\n",
              "Institutional Ownership\n",
              "80.9%\n",
              "Total Revenue (TTM)\n",
              "\\$80,539.00\n",
              "3/31/2024\n",
              "Revenue Growth\n",
              "(TTM vs. Prior TTM)</td>\n",
              "      <td><div class=\"pxt_document\" style=\"width:320px;\">\n",
              "            <a href=\"http://127.0.0.1:37823/root/.pixeltable/file_cache/a78998445ed645619614caa73d83a84c_0_a3b5f048384678987f216fbaa7ebeace9a9a89e117fd364f4ab50b677456f9d3.pdf\">\n",
              "                <img style=\"object-fit: contain; border: 1px solid black;\" src=\"\" />\n",
              "            </a>\n",
              "        </div></td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>"
            ],
            "text/plain": [
              "    pos                                               text  \\\n",
              "0    19   other customers.\\nHowever, clients and prospe...   \n",
              "1    18   this report constitutes\\nindividual investmen...   \n",
              "2    17  is registered with the U.S. Securities and Exc...   \n",
              "3    16   premium relative\\nP/E in the 1.5- to 1.7-time...   \n",
              "4    15   to entry, the consulting business can be quit...   \n",
              "5    14   to retire in September 2024.\\nWe expect to se...   \n",
              "6    13   of $8.7-$9.3 billion for FY24. For FY23, free...   \n",
              "7    12  .20; the new guidance implies growth of 2%-3% ...   \n",
              "8    11  For all of FY23, Accenture generated record re...   \n",
              "9    10   (ended May 31, 2024), Accenture reported reve...   \n",
              "10    9   at North American communications and media cu...   \n",
              "11    8   Capital Markets. North American operating pro...   \n",
              "12    7  28 billion (44% of total) rose 4% from the pri...   \n",
              "13    6  both niche capabilities and geographic breadth...   \n",
              "14    5   The company has moved quickly to adjust to lo...   \n",
              "15    4  36% in 2022, versus a 30% decline for peers; a...   \n",
              "16    3  ure is investing\\ninorganically to expand its ...   \n",
              "17    2  ly on June 20, despite the company reporting f...   \n",
              "18    1   500 lower by 0.79% and 0.25%,\\nrespectively. ...   \n",
              "19    0  MARKET DIGEST\\n- 1 -\\n FRIDAY, JUNE 21, 2024\\n...   \n",
              "20   13   subject\\nto change without notice and Fidelit...   \n",
              "21   12  2024:\\n$176.30\\nCommunication Services Sector\\...   \n",
              "22   11  . equity securities in each industry to which ...   \n",
              "23   10  .4\\n1.5\\n--\\nEnterprise Value\\n$0.00\\n$0.00\\n-...   \n",
              "24    9  /B/E/S from Refinitiv\\nEarnings in US Dollars\\...   \n",
              "25    8   (PDF).\\nCompany Research Highlights\\n®\\nGOOGL...   \n",
              "26    7  i) after the Firm Name indicates an\\nindepende...   \n",
              "27    6  04/25/24\\nOverweight\\nTruist Securities, Inc\\n...   \n",
              "28    5  KeyBanc Capital Markets\\nBuy\\n \\n0.74%\\n05/14/...   \n",
              "29    4   Provided by StarMine from Refinitiv as of 6/2...   \n",
              "30    3   on 6/20/2024:\\n$176.30\\nCommunication Service...   \n",
              "31    2  \\n6.0\\n   200-Day Average\\n22.6\\nPrice Perform...   \n",
              "32    1  +11.78%\\nEnterprise Value\\n$2103.1 B\\n6/20/202...   \n",
              "33    0  Company Research Highlights\\n®\\nReport created...   \n",
              "\n",
              "                                                  pdf  \n",
              "0   /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "1   /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "2   /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "3   /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "4   /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "5   /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "6   /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "7   /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "8   /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "9   /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "10  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "11  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "12  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "13  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "14  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "15  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "16  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "17  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "18  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "19  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "20  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "21  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "22  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "23  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "24  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "25  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "26  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "27  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "28  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "29  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "30  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "31  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "32  /root/.pixeltable/file_cache/a78998445ed645619...  \n",
              "33  /root/.pixeltable/file_cache/a78998445ed645619...  "
            ]
          },
          "execution_count": 70,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "documents_chunks.collect()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XLIO8R-J_2Os"
      },
      "source": [
        "## Tools\n",
        "\n",
        "This section defines custom tools that extend the AI agent's capabilities beyond text generation. These tools demonstrate how to create specialized functions for specific domains and use cases."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 71,
      "metadata": {
        "id": "5QYa1VuW4mJ1"
      },
      "outputs": [],
      "source": [
        "@pxt.query\n",
        "def find_documents(query: str) -> dict:\n",
        "    \"\"\"Function to return top five chunks from financial documents that are most similar to query, ranked by vector similarity for use of RAG.\"\"\"\n",
        "    # Calculate the similarity between the query and the text of the document chunks using the 'similarity' function\n",
        "    sim = documents_chunks.text.similarity(query)\n",
        "    # Order the document chunks by similarity in descending order, select the text and similarity score, and limit to the top 5 results\n",
        "    return (\n",
        "        documents_chunks.order_by(sim, asc=False)\n",
        "        .select(\n",
        "            documents_chunks.text,\n",
        "            similarity=sim\n",
        "        )\n",
        "        .limit(5)\n",
        "    )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fAlxEw0nvLpH"
      },
      "source": [
        "MCP allows to use of tools exposed by the MCP server and integrates external services and custom logic into agentic workflows. Tools exposed by the MCP server can be used as Pixeltable UDFs."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3wX48jzd5kiF"
      },
      "outputs": [],
      "source": [
        "# Connect to the Alpha Vantage stock market MCP server. \n",
        "# For an API key, visit https://www.alphavantage.co/support/#api-key\n",
        "# This returns a list of UDFs, one for each tool.\n",
        "\n",
        "api_key = \"<api-key>\"  # TODO: Replace <api-key> with your actual Alpha Vantage API key.\n",
        "udfs = pxt.mcp_udfs(f\"https://mcp.alphavantage.co/mcp?apikey={api_key}\")\n",
        "\n",
        "# Get available tools with: print(list(enumerate(udfs)))\n",
        "get_exchange_rate = udfs[30]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0Ve0G4qz__cb"
      },
      "source": [
        "## Agent\n",
        "\n",
        "This section creates an intelligent AI agent that combines conversational capabilities with specialized tools. The agent represents the core orchestrator of our context engineering system."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 73,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "yQdnTg1FdRLi",
        "outputId": "3cd0b3c6-eebd-42b3-d96e-26dcd2aa3382"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Created directory 'context_engineering.agent'.\n",
            "Created table 'memory'.\n",
            "Created table 'agent'.\n",
            "Created table 'tools'.\n",
            "Added 0 column values with 0 errors.\n",
            "Added 0 column values with 0 errors.\n",
            "Added 0 column values with 0 errors.\n",
            "Added 0 column values with 0 errors.\n",
            "Added 0 column values with 0 errors.\n",
            "Added 0 column values with 0 errors.\n",
            "Added 0 column values with 0 errors.\n",
            "Added 0 column values with 0 errors.\n",
            "Added 0 column values with 0 errors.\n"
          ]
        }
      ],
      "source": [
        "from pixelagent.openai import Agent\n",
        "\n",
        "# Define and initialize the Agent\n",
        "tools_agent = Agent(\n",
        "    name = \"context_engineering.agent\", # Name of the agent\n",
        "    system_prompt=(\n",
        "        \"You are a tools-enabled AI assistant. \"\n",
        "        \"Use `find_documents` for RAG/PDF-Search to retrieve the top-5 chunks as per user query and answer ONLY from those. \"\n",
        "        \"If context is insufficient, say so explicitly. \"\n",
        "        \"Use `get_exchange_rate` for realtime exchange rate for any pair of cryptocurrency (e.g., Bitcoin) or physical currency (e.g., USD). \"\n",
        "        \"Be concise, factual, and avoid recursive tool calls.\"\n",
        "    ),\n",
        "    tools=pxt.tools(find_documents, get_exchange_rate), # Register the tools the agent can use\n",
        "    reset=False, # Do not reset the agent's memory on initialization\n",
        "    n_latest_messages=None # Keep all messages in memory\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WoSAhYG2AFSa"
      },
      "source": [
        "## Tool Calling\n",
        "\n",
        "This section demonstrates the agent in action, showcasing how it intelligently selects and uses appropriate tools based on the query content."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 74,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "asVzPvPPmSBV",
        "outputId": "803716b2-6b85-44fb-d801-aa1d9766a595"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Inserting rows into `memory`: 1 rows [00:00, 205.36 rows/s]\n",
            "Inserted 1 row with 0 errors.\n",
            "Inserting rows into `tools`: 1 rows [00:00, 156.07 rows/s]\n",
            "Inserted 1 row with 0 errors.\n",
            "Inserting rows into `memory`: 1 rows [00:00, 356.33 rows/s]\n",
            "Inserted 1 row with 0 errors.\n",
            "In its recent earnings report for Q1 2024, Alphabet Inc. (NASDAQ: GOOGL) reported earnings of $1.89 per share, exceeding both the First Call Consensus estimate of $1.515 and the StarMine SmartEstimate of $1.533. The company's stock was priced at $176.30 on June 20, 2024, with a market capitalization of approximately $2.18 trillion. Alphabet operates through three main segments: Google Services, Google Cloud, and Other Bets, with total revenue for the trailing twelve months (TTM) at $80.54 billion. The company has shown a revenue growth of 11.8% compared to the prior TTM, and its institutional ownership stands at 80.9%. The next earnings report is expected on July 23, 2024.\n"
          ]
        }
      ],
      "source": [
        "# Call the agent with a query to get a response using its defined tools.\n",
        "print(tools_agent.tool_call(\"Give me a brief summary about Alphabet earnings.\"))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "oXcxYR2omkGd",
        "outputId": "1aaecf4d-7f82-4675-eae8-a55516249b08"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Inserting rows into `memory`: 1 rows [00:00, 297.66 rows/s]\n",
            "Inserted 1 row with 0 errors.\n",
            "Inserting rows into `tools`: 1 rows [00:00, 288.47 rows/s]\n",
            "Inserted 1 row with 0 errors.\n",
            "Inserting rows into `memory`: 1 rows [00:00, 327.86 rows/s]\n",
            "Inserted 1 row with 0 errors.\n",
            "The exchange rate between Bitcoin (BTC) and the United States Dollar (USD) is approximately 91,420.56 USD for 1 BTC. Please note that this exchange rate is subject to change due to market fluctuations.\n"
          ]
        }
      ],
      "source": [
        "# Call the agent with a query to get the exchange rate between USD and BTC\n",
        "print(tools_agent.tool_call(\"What is the exchange rate between USD and bitcoin?\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FLzfF9NsOMPR"
      },
      "source": [
        "# Memory Management"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XtwrbRX8AJcQ"
      },
      "source": [
        "## Short-term Memory\n",
        "\n",
        "This section explores the sophisticated memory system that enables the agent to maintain context across conversations and learn from interactions over time. The memory system operates on multiple levels to provide comprehensive context engineering."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 76,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 365
        },
        "id": "8I2fB7AmqrEl",
        "outputId": "670b136f-6ff9-4afa-d88f-1fe8cc09b7cd"
      },
      "outputs": [
        {
          "data": {
            "text/html": [
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th>message_id</th>\n",
              "      <th>role</th>\n",
              "      <th>content</th>\n",
              "      <th>timestamp</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <td>133bdf1e-937a-40e2-9626-7356939b1545</td>\n",
              "      <td>user</td>\n",
              "      <td>Give me a brief summary about Alphabet earnings.</td>\n",
              "      <td>2025-11-19 11:53:39.900677+00:00</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>d55a8f7b-bb75-4b1a-88b4-95c9ac284803</td>\n",
              "      <td>assistant</td>\n",
              "      <td>In its recent earnings report for Q1 2024, Alphabet Inc. (NASDAQ: GOOGL) reported earnings of \\$1.89 per share, exceeding both the First Call Consensus estimate of \\$1.515 and the StarMine SmartEstimate of \\$1.533. The company&#x27;s stock was priced at \\$176.30 on June 20, 2024, with a market capitalization of approximately \\$2.18 trillion. Alphabet operates through three main segments: Google Services, Google Cloud, and Other Bets, with total revenue for the trailing twelve months (TTM) at \\$80.54 billion. The company has shown a revenue growth of 11.8% compared to the prior TTM, and its institutional ownership stands at 80.9%. The next earnings report is expected on July 23, 2024.</td>\n",
              "      <td>2025-11-19 11:53:46.460504+00:00</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>c4085f9d-22d2-4f8b-a6a0-546077c8532e</td>\n",
              "      <td>user</td>\n",
              "      <td>What is the exchange rate between USD and bitcoin?</td>\n",
              "      <td>2025-11-19 11:54:21.028021+00:00</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>a1b0298f-cbda-48a2-bd65-61f1abc4a12c</td>\n",
              "      <td>assistant</td>\n",
              "      <td>The exchange rate between Bitcoin (BTC) and the United States Dollar (USD) is approximately 91,420.56 USD for 1 BTC. Please note that this exchange rate is subject to change due to market fluctuations.</td>\n",
              "      <td>2025-11-19 11:54:24.669192+00:00</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>"
            ],
            "text/plain": [
              "                             message_id       role  \\\n",
              "0  133bdf1e-937a-40e2-9626-7356939b1545       user   \n",
              "1  d55a8f7b-bb75-4b1a-88b4-95c9ac284803  assistant   \n",
              "2  c4085f9d-22d2-4f8b-a6a0-546077c8532e       user   \n",
              "3  a1b0298f-cbda-48a2-bd65-61f1abc4a12c  assistant   \n",
              "\n",
              "                                             content  \\\n",
              "0   Give me a brief summary about Alphabet earnings.   \n",
              "1  In its recent earnings report for Q1 2024, Alp...   \n",
              "2  What is the exchange rate between USD and bitc...   \n",
              "3  The exchange rate between Bitcoin (BTC) and th...   \n",
              "\n",
              "                         timestamp  \n",
              "0 2025-11-19 11:53:39.900677+00:00  \n",
              "1 2025-11-19 11:53:46.460504+00:00  \n",
              "2 2025-11-19 11:54:21.028021+00:00  \n",
              "3 2025-11-19 11:54:24.669192+00:00  "
            ]
          },
          "execution_count": 76,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Get the memory table associated with the agent.\n",
        "memory = pxt.get_table(\"context_engineering.agent.memory\")\n",
        "# Collect all data from the memory table.\n",
        "memory.collect()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 77,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "XFTpcjiytY6o",
        "outputId": "07c5129e-fe59-4b2e-8bb3-50bc6b9cb1ea"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "user: Give me a brief summary about Alphabet earnings.\n",
            "assistant: In its recent earnings report for Q1 2024, Alphabet Inc. (NASDAQ: GOOGL) reported earnings of $1.89 per share, exceeding both the First Call Consensus estimate of $1.515 and the StarMine SmartEstimate of $1.533. The company's stock was priced at $176.30 on June 20, 2024, with a market capitalization of approximately $2.18 trillion. Alphabet operates through three main segments: Google Services, Google Cloud, and Other Bets, with total revenue for the trailing twelve months (TTM) at $80.54 billion. The company has shown a revenue growth of 11.8% compared to the prior TTM, and its institutional ownership stands at 80.9%. The next earnings report is expected on July 23, 2024.\n",
            "user: What is the exchange rate between USD and bitcoin?\n",
            "assistant: The exchange rate between Bitcoin (BTC) and the United States Dollar (USD) is approximately 91,420.56 USD for 1 BTC. Please note that this exchange rate is subject to change due to market fluctuations.\n",
            "\n"
          ]
        }
      ],
      "source": [
        "# Initialize an empty string to store the chat history\n",
        "chat_history = \"\"\n",
        "# Get the memory table from the Pixeltable database\n",
        "memory = pxt.get_table(\"context_engineering.agent.memory\")\n",
        "\n",
        "# Collect the 'role' and 'content' columns from the memory table into a pandas DataFrame\n",
        "df = memory.select(memory.role, memory.content).collect()\n",
        "# Iterate through the DataFrame rows and format the chat history\n",
        "for role, content in zip(df[\"role\"], df[\"content\"]):\n",
        "    chat_history += f\"{role}: {content}\\n\"\n",
        "\n",
        "# Print the formatted chat history\n",
        "print(chat_history)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QIfJ45v9ASo4"
      },
      "source": [
        "## Long-term Memory\n",
        "\n",
        "**Purpose**: Creates persistent, searchable memory that enables semantic retrieval of historical interactions."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 78,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Dlwsfp_-wUNo",
        "outputId": "b7896b70-e5cc-4767-dea0-1e46386f909d"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Added 4 column values with 0 errors.\n",
            "Added 4 column values with 0 errors.\n"
          ]
        }
      ],
      "source": [
        "import pixeltable.functions as pxtf\n",
        "from pixeltable.functions import huggingface\n",
        "\n",
        "# Get the memory table from the Pixeltable database\n",
        "memory = pxt.get_table(\"context_engineering.agent.memory\")\n",
        "\n",
        "# Add a computed column 'user_content' to the memory table by formatting the 'role' and 'content' columns\n",
        "memory.add_computed_column(\n",
        "    user_content=pxtf.string.format(\n",
        "        \"{0}: {1}\", memory.role, memory.content\n",
        "    ),\n",
        "    if_exists=\"ignore\", # Ignore if the column already exists\n",
        ")\n",
        "# Add a computed column 'embedding' to the memory table by applying the sentence_transformer function to the 'user_content' column\n",
        "memory.add_computed_column(\n",
        "    embedding=huggingface.sentence_transformer(memory.user_content, model_id='intfloat/e5-large-v2')\n",
        ")\n",
        "\n",
        "# Add an embedding index to the 'user_content' column for faster similarity search\n",
        "memory.add_embedding_index(\n",
        "    column=\"user_content\",\n",
        "    idx_name=\"user_content_idx\", # Name of the index\n",
        "    embedding=embed_model, # Embedding model to use\n",
        "    if_exists=\"ignore\", # Ignore if the index already exists\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 79,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 660
        },
        "id": "vcKrWHjVxdXK",
        "outputId": "c39a8fbb-67ce-48fe-a8ad-75e76353603e"
      },
      "outputs": [
        {
          "data": {
            "text/html": [
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th>message_id</th>\n",
              "      <th>role</th>\n",
              "      <th>content</th>\n",
              "      <th>timestamp</th>\n",
              "      <th>user_content</th>\n",
              "      <th>embedding</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <td>133bdf1e-937a-40e2-9626-7356939b1545</td>\n",
              "      <td>user</td>\n",
              "      <td>Give me a brief summary about Alphabet earnings.</td>\n",
              "      <td>2025-11-19 11:53:39.900677+00:00</td>\n",
              "      <td>user: Give me a brief summary about Alphabet earnings.</td>\n",
              "      <td>[ 0.038 -0.072  0.03  -0.009 -0.038  0.062 ...  0.003 -0.008  0.012 -0.018  0.039  0.013]</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>d55a8f7b-bb75-4b1a-88b4-95c9ac284803</td>\n",
              "      <td>assistant</td>\n",
              "      <td>In its recent earnings report for Q1 2024, Alphabet Inc. (NASDAQ: GOOGL) reported earnings of \\$1.89 per share, exceeding both the First Call Consensus estimate of \\$1.515 and the StarMine SmartEstimate of \\$1.533. The company&#x27;s stock was priced at \\$176.30 on June 20, 2024, with a market capitalization of approximately \\$2.18 trillion. Alphabet operates through three main segments: Google Services, Google Cloud, and Other Bets, with total revenue for the trailing twelve months (TTM) at \\$80.54 billion. The company has shown a revenue growth of 11.8% compared to the prior TTM, and its institutional ownership stands at 80.9%. The next earnings report is expected on July 23, 2024.</td>\n",
              "      <td>2025-11-19 11:53:46.460504+00:00</td>\n",
              "      <td>assistant: In its recent earnings report for Q1 2024, Alphabet Inc. (NASDAQ: GOOGL) reported earnings of \\$1.89 per share, exceeding both the First Call Consensus estimate of \\$1.515 and the StarMine SmartEstimate of \\$1.533. The company&#x27;s stock was priced at \\$176.30 on June 20, 2024, with a market capitalization of approximately \\$2.18 trillion. Alphabet operates through three main segments: Google Services, Google Cloud, and Other Bets, with total revenue for the trailing twelve months (TTM) at \\$80.54 billion. The company has shown a revenue growth of 11.8% compared to the prior TTM, and its institutional ownership stands at 80.9%. The next earnings report is expected on July 23, 2024.</td>\n",
              "      <td>[ 0.    -0.055  0.017 -0.004 -0.04   0.065 ...  0.036 -0.009  0.005 -0.043  0.073  0.005]</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>c4085f9d-22d2-4f8b-a6a0-546077c8532e</td>\n",
              "      <td>user</td>\n",
              "      <td>What is the exchange rate between USD and bitcoin?</td>\n",
              "      <td>2025-11-19 11:54:21.028021+00:00</td>\n",
              "      <td>user: What is the exchange rate between USD and bitcoin?</td>\n",
              "      <td>[ 0.033 -0.073  0.035 -0.033 -0.068  0.046 ... -0.015 -0.032  0.044 -0.017 -0.025  0.023]</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>a1b0298f-cbda-48a2-bd65-61f1abc4a12c</td>\n",
              "      <td>assistant</td>\n",
              "      <td>The exchange rate between Bitcoin (BTC) and the United States Dollar (USD) is approximately 91,420.56 USD for 1 BTC. Please note that this exchange rate is subject to change due to market fluctuations.</td>\n",
              "      <td>2025-11-19 11:54:24.669192+00:00</td>\n",
              "      <td>assistant: The exchange rate between Bitcoin (BTC) and the United States Dollar (USD) is approximately 91,420.56 USD for 1 BTC. Please note that this exchange rate is subject to change due to market fluctuations.</td>\n",
              "      <td>[ 0.034 -0.048  0.016 -0.034 -0.082  0.049 ... -0.    -0.028  0.032 -0.022  0.006  0.038]</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>"
            ],
            "text/plain": [
              "                             message_id       role  \\\n",
              "0  133bdf1e-937a-40e2-9626-7356939b1545       user   \n",
              "1  d55a8f7b-bb75-4b1a-88b4-95c9ac284803  assistant   \n",
              "2  c4085f9d-22d2-4f8b-a6a0-546077c8532e       user   \n",
              "3  a1b0298f-cbda-48a2-bd65-61f1abc4a12c  assistant   \n",
              "\n",
              "                                             content  \\\n",
              "0   Give me a brief summary about Alphabet earnings.   \n",
              "1  In its recent earnings report for Q1 2024, Alp...   \n",
              "2  What is the exchange rate between USD and bitc...   \n",
              "3  The exchange rate between Bitcoin (BTC) and th...   \n",
              "\n",
              "                         timestamp  \\\n",
              "0 2025-11-19 11:53:39.900677+00:00   \n",
              "1 2025-11-19 11:53:46.460504+00:00   \n",
              "2 2025-11-19 11:54:21.028021+00:00   \n",
              "3 2025-11-19 11:54:24.669192+00:00   \n",
              "\n",
              "                                        user_content  \\\n",
              "0  user: Give me a brief summary about Alphabet e...   \n",
              "1  assistant: In its recent earnings report for Q...   \n",
              "2  user: What is the exchange rate between USD an...   \n",
              "3  assistant: The exchange rate between Bitcoin (...   \n",
              "\n",
              "                                           embedding  \n",
              "0  [0.038295243, -0.07218907, 0.029813364, -0.008...  \n",
              "1  [0.00032986247, -0.05505832, 0.016880741, -0.0...  \n",
              "2  [0.032953136, -0.073314324, 0.03461188, -0.032...  \n",
              "3  [0.03403786, -0.048384063, 0.016288206, -0.034...  "
            ]
          },
          "execution_count": 79,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Get the memory table from the Pixeltable database\n",
        "memory = pxt.get_table(\"context_engineering.agent.memory\")\n",
        "# Collect all data from the memory table into a pandas DataFrame\n",
        "memory.collect()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1RiHeDKnAYTc"
      },
      "source": [
        "### Integrate VectorDB\n",
        "\n",
        "**Purpose**: Demonstrates integration with external vector databases for scalable memory management and advanced analytics."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 80,
      "metadata": {
        "id": "rklOF-6syq9d"
      },
      "outputs": [],
      "source": [
        "from pathlib import Path\n",
        "\n",
        "# Get the memory table from the Pixeltable database\n",
        "memory = pxt.get_table(\"context_engineering.agent.memory\")\n",
        "# Collect all data from the memory table\n",
        "memory.collect()\n",
        "\n",
        "# Export selected columns (message_id, user_content, embedding) from the memory table\n",
        "# to a LanceDB database located at 'vector_db' with a table named 'semantic_memory'.\n",
        "# If the table exists, append the data.\n",
        "pxt.io.export_lancedb(\n",
        "    memory.select(memory.message_id, memory.user_content, memory.embedding),\n",
        "    Path('vector_db'),\n",
        "    'semantic_memory',\n",
        "    if_exists='append'\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 174
        },
        "id": "knhCdg4SH9WU",
        "outputId": "d8447231-f691-4747-b578-6ccf975021ae"
      },
      "outputs": [
        {
          "data": {
            "application/vnd.google.colaboratory.intrinsic+json": {
              "summary": "{\n  \"name\": \"results\",\n  \"rows\": 4,\n  \"fields\": [\n    {\n      \"column\": \"message_id\",\n      \"properties\": {\n        \"dtype\": \"string\",\n        \"num_unique_values\": 4,\n        \"samples\": [\n          \"d55a8f7b-bb75-4b1a-88b4-95c9ac284803\",\n          \"a1b0298f-cbda-48a2-bd65-61f1abc4a12c\",\n          \"133bdf1e-937a-40e2-9626-7356939b1545\"\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"user_content\",\n      \"properties\": {\n        \"dtype\": \"string\",\n        \"num_unique_values\": 4,\n        \"samples\": [\n          \"assistant: In its recent earnings report for Q1 2024, Alphabet Inc. (NASDAQ: GOOGL) reported earnings of $1.89 per share, exceeding both the First Call Consensus estimate of $1.515 and the StarMine SmartEstimate of $1.533. The company's stock was priced at $176.30 on June 20, 2024, with a market capitalization of approximately $2.18 trillion. Alphabet operates through three main segments: Google Services, Google Cloud, and Other Bets, with total revenue for the trailing twelve months (TTM) at $80.54 billion. The company has shown a revenue growth of 11.8% compared to the prior TTM, and its institutional ownership stands at 80.9%. The next earnings report is expected on July 23, 2024.\",\n          \"assistant: The exchange rate between Bitcoin (BTC) and the United States Dollar (USD) is approximately 91,420.56 USD for 1 BTC. Please note that this exchange rate is subject to change due to market fluctuations.\",\n          \"user: Give me a brief summary about Alphabet earnings.\"\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"embedding\",\n      \"properties\": {\n        \"dtype\": \"object\",\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    }\n  ]\n}",
              "type": "dataframe",
              "variable_name": "results"
            },
            "text/html": [
              "\n",
              "  <div id=\"df-655ce50b-2711-4329-8747-22570e2e6d65\" class=\"colab-df-container\">\n",
              "    <div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>message_id</th>\n",
              "      <th>user_content</th>\n",
              "      <th>embedding</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>133bdf1e-937a-40e2-9626-7356939b1545</td>\n",
              "      <td>user: Give me a brief summary about Alphabet e...</td>\n",
              "      <td>[0.038295243, -0.07218907, 0.029813364, -0.008...</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>d55a8f7b-bb75-4b1a-88b4-95c9ac284803</td>\n",
              "      <td>assistant: In its recent earnings report for Q...</td>\n",
              "      <td>[0.00032986247, -0.05505832, 0.016880741, -0.0...</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>c4085f9d-22d2-4f8b-a6a0-546077c8532e</td>\n",
              "      <td>user: What is the exchange rate between USD an...</td>\n",
              "      <td>[0.032953136, -0.073314324, 0.03461188, -0.032...</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>a1b0298f-cbda-48a2-bd65-61f1abc4a12c</td>\n",
              "      <td>assistant: The exchange rate between Bitcoin (...</td>\n",
              "      <td>[0.03403786, -0.048384063, 0.016288206, -0.034...</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>\n",
              "    <div class=\"colab-df-buttons\">\n",
              "\n",
              "  <div class=\"colab-df-container\">\n",
              "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-655ce50b-2711-4329-8747-22570e2e6d65')\"\n",
              "            title=\"Convert this dataframe to an interactive table.\"\n",
              "            style=\"display:none;\">\n",
              "\n",
              "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
              "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
              "  </svg>\n",
              "    </button>\n",
              "\n",
              "  <style>\n",
              "    .colab-df-container {\n",
              "      display:flex;\n",
              "      gap: 12px;\n",
              "    }\n",
              "\n",
              "    .colab-df-convert {\n",
              "      background-color: #E8F0FE;\n",
              "      border: none;\n",
              "      border-radius: 50%;\n",
              "      cursor: pointer;\n",
              "      display: none;\n",
              "      fill: #1967D2;\n",
              "      height: 32px;\n",
              "      padding: 0 0 0 0;\n",
              "      width: 32px;\n",
              "    }\n",
              "\n",
              "    .colab-df-convert:hover {\n",
              "      background-color: #E2EBFA;\n",
              "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
              "      fill: #174EA6;\n",
              "    }\n",
              "\n",
              "    .colab-df-buttons div {\n",
              "      margin-bottom: 4px;\n",
              "    }\n",
              "\n",
              "    [theme=dark] .colab-df-convert {\n",
              "      background-color: #3B4455;\n",
              "      fill: #D2E3FC;\n",
              "    }\n",
              "\n",
              "    [theme=dark] .colab-df-convert:hover {\n",
              "      background-color: #434B5C;\n",
              "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
              "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
              "      fill: #FFFFFF;\n",
              "    }\n",
              "  </style>\n",
              "\n",
              "    <script>\n",
              "      const buttonEl =\n",
              "        document.querySelector('#df-655ce50b-2711-4329-8747-22570e2e6d65 button.colab-df-convert');\n",
              "      buttonEl.style.display =\n",
              "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
              "\n",
              "      async function convertToInteractive(key) {\n",
              "        const element = document.querySelector('#df-655ce50b-2711-4329-8747-22570e2e6d65');\n",
              "        const dataTable =\n",
              "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
              "                                                    [key], {});\n",
              "        if (!dataTable) return;\n",
              "\n",
              "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
              "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
              "          + ' to learn more about interactive tables.';\n",
              "        element.innerHTML = '';\n",
              "        dataTable['output_type'] = 'display_data';\n",
              "        await google.colab.output.renderOutput(dataTable, element);\n",
              "        const docLink = document.createElement('div');\n",
              "        docLink.innerHTML = docLinkHtml;\n",
              "        element.appendChild(docLink);\n",
              "      }\n",
              "    </script>\n",
              "  </div>\n",
              "\n",
              "\n",
              "    <div id=\"df-795730b6-9ab8-4398-afca-1e1600ad5d2c\">\n",
              "      <button class=\"colab-df-quickchart\" onclick=\"quickchart('df-795730b6-9ab8-4398-afca-1e1600ad5d2c')\"\n",
              "                title=\"Suggest charts\"\n",
              "                style=\"display:none;\">\n",
              "\n",
              "<svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
              "     width=\"24px\">\n",
              "    <g>\n",
              "        <path d=\"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z\"/>\n",
              "    </g>\n",
              "</svg>\n",
              "      </button>\n",
              "\n",
              "<style>\n",
              "  .colab-df-quickchart {\n",
              "      --bg-color: #E8F0FE;\n",
              "      --fill-color: #1967D2;\n",
              "      --hover-bg-color: #E2EBFA;\n",
              "      --hover-fill-color: #174EA6;\n",
              "      --disabled-fill-color: #AAA;\n",
              "      --disabled-bg-color: #DDD;\n",
              "  }\n",
              "\n",
              "  [theme=dark] .colab-df-quickchart {\n",
              "      --bg-color: #3B4455;\n",
              "      --fill-color: #D2E3FC;\n",
              "      --hover-bg-color: #434B5C;\n",
              "      --hover-fill-color: #FFFFFF;\n",
              "      --disabled-bg-color: #3B4455;\n",
              "      --disabled-fill-color: #666;\n",
              "  }\n",
              "\n",
              "  .colab-df-quickchart {\n",
              "    background-color: var(--bg-color);\n",
              "    border: none;\n",
              "    border-radius: 50%;\n",
              "    cursor: pointer;\n",
              "    display: none;\n",
              "    fill: var(--fill-color);\n",
              "    height: 32px;\n",
              "    padding: 0;\n",
              "    width: 32px;\n",
              "  }\n",
              "\n",
              "  .colab-df-quickchart:hover {\n",
              "    background-color: var(--hover-bg-color);\n",
              "    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
              "    fill: var(--button-hover-fill-color);\n",
              "  }\n",
              "\n",
              "  .colab-df-quickchart-complete:disabled,\n",
              "  .colab-df-quickchart-complete:disabled:hover {\n",
              "    background-color: var(--disabled-bg-color);\n",
              "    fill: var(--disabled-fill-color);\n",
              "    box-shadow: none;\n",
              "  }\n",
              "\n",
              "  .colab-df-spinner {\n",
              "    border: 2px solid var(--fill-color);\n",
              "    border-color: transparent;\n",
              "    border-bottom-color: var(--fill-color);\n",
              "    animation:\n",
              "      spin 1s steps(1) infinite;\n",
              "  }\n",
              "\n",
              "  @keyframes spin {\n",
              "    0% {\n",
              "      border-color: transparent;\n",
              "      border-bottom-color: var(--fill-color);\n",
              "      border-left-color: var(--fill-color);\n",
              "    }\n",
              "    20% {\n",
              "      border-color: transparent;\n",
              "      border-left-color: var(--fill-color);\n",
              "      border-top-color: var(--fill-color);\n",
              "    }\n",
              "    30% {\n",
              "      border-color: transparent;\n",
              "      border-left-color: var(--fill-color);\n",
              "      border-top-color: var(--fill-color);\n",
              "      border-right-color: var(--fill-color);\n",
              "    }\n",
              "    40% {\n",
              "      border-color: transparent;\n",
              "      border-right-color: var(--fill-color);\n",
              "      border-top-color: var(--fill-color);\n",
              "    }\n",
              "    60% {\n",
              "      border-color: transparent;\n",
              "      border-right-color: var(--fill-color);\n",
              "    }\n",
              "    80% {\n",
              "      border-color: transparent;\n",
              "      border-right-color: var(--fill-color);\n",
              "      border-bottom-color: var(--fill-color);\n",
              "    }\n",
              "    90% {\n",
              "      border-color: transparent;\n",
              "      border-bottom-color: var(--fill-color);\n",
              "    }\n",
              "  }\n",
              "</style>\n",
              "\n",
              "      <script>\n",
              "        async function quickchart(key) {\n",
              "          const quickchartButtonEl =\n",
              "            document.querySelector('#' + key + ' button');\n",
              "          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.\n",
              "          quickchartButtonEl.classList.add('colab-df-spinner');\n",
              "          try {\n",
              "            const charts = await google.colab.kernel.invokeFunction(\n",
              "                'suggestCharts', [key], {});\n",
              "          } catch (error) {\n",
              "            console.error('Error during call to suggestCharts:', error);\n",
              "          }\n",
              "          quickchartButtonEl.classList.remove('colab-df-spinner');\n",
              "          quickchartButtonEl.classList.add('colab-df-quickchart-complete');\n",
              "        }\n",
              "        (() => {\n",
              "          let quickchartButtonEl =\n",
              "            document.querySelector('#df-795730b6-9ab8-4398-afca-1e1600ad5d2c button');\n",
              "          quickchartButtonEl.style.display =\n",
              "            google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
              "        })();\n",
              "      </script>\n",
              "    </div>\n",
              "\n",
              "  <div id=\"id_420db871-4d24-42e3-8b44-afea31f84915\">\n",
              "    <style>\n",
              "      .colab-df-generate {\n",
              "        background-color: #E8F0FE;\n",
              "        border: none;\n",
              "        border-radius: 50%;\n",
              "        cursor: pointer;\n",
              "        display: none;\n",
              "        fill: #1967D2;\n",
              "        height: 32px;\n",
              "        padding: 0 0 0 0;\n",
              "        width: 32px;\n",
              "      }\n",
              "\n",
              "      .colab-df-generate:hover {\n",
              "        background-color: #E2EBFA;\n",
              "        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
              "        fill: #174EA6;\n",
              "      }\n",
              "\n",
              "      [theme=dark] .colab-df-generate {\n",
              "        background-color: #3B4455;\n",
              "        fill: #D2E3FC;\n",
              "      }\n",
              "\n",
              "      [theme=dark] .colab-df-generate:hover {\n",
              "        background-color: #434B5C;\n",
              "        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
              "        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
              "        fill: #FFFFFF;\n",
              "      }\n",
              "    </style>\n",
              "    <button class=\"colab-df-generate\" onclick=\"generateWithVariable('results')\"\n",
              "            title=\"Generate code using this dataframe.\"\n",
              "            style=\"display:none;\">\n",
              "\n",
              "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
              "       width=\"24px\">\n",
              "    <path d=\"M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z\"/>\n",
              "  </svg>\n",
              "    </button>\n",
              "    <script>\n",
              "      (() => {\n",
              "      const buttonEl =\n",
              "        document.querySelector('#id_420db871-4d24-42e3-8b44-afea31f84915 button.colab-df-generate');\n",
              "      buttonEl.style.display =\n",
              "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
              "\n",
              "      buttonEl.onclick = () => {\n",
              "        google.colab.notebook.generateWithVariable('results');\n",
              "      }\n",
              "      })();\n",
              "    </script>\n",
              "  </div>\n",
              "\n",
              "    </div>\n",
              "  </div>\n"
            ],
            "text/plain": [
              "                             message_id  \\\n",
              "0  133bdf1e-937a-40e2-9626-7356939b1545   \n",
              "1  d55a8f7b-bb75-4b1a-88b4-95c9ac284803   \n",
              "2  c4085f9d-22d2-4f8b-a6a0-546077c8532e   \n",
              "3  a1b0298f-cbda-48a2-bd65-61f1abc4a12c   \n",
              "\n",
              "                                        user_content  \\\n",
              "0  user: Give me a brief summary about Alphabet e...   \n",
              "1  assistant: In its recent earnings report for Q...   \n",
              "2  user: What is the exchange rate between USD an...   \n",
              "3  assistant: The exchange rate between Bitcoin (...   \n",
              "\n",
              "                                           embedding  \n",
              "0  [0.038295243, -0.07218907, 0.029813364, -0.008...  \n",
              "1  [0.00032986247, -0.05505832, 0.016880741, -0.0...  \n",
              "2  [0.032953136, -0.073314324, 0.03461188, -0.032...  \n",
              "3  [0.03403786, -0.048384063, 0.016288206, -0.034...  "
            ]
          },
          "execution_count": 81,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "import lancedb\n",
        "\n",
        "# Connect to the LanceDB database located at 'vector_db'\n",
        "db = lancedb.connect('vector_db')\n",
        "# Open the 'semantic_memory' table in the database and convert it to a pandas DataFrame\n",
        "results = db.open_table('semantic_memory').to_pandas()\n",
        "# Display the resulting DataFrame\n",
        "results"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jssmgjB7AuEY"
      },
      "source": [
        "### Vector Search\n",
        "\n",
        "**Purpose**: Implements sophisticated semantic search capabilities for memory retrieval using advanced vector similarity techniques."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 82,
      "metadata": {
        "id": "qnGf1KqZUAG-"
      },
      "outputs": [],
      "source": [
        "import lancedb\n",
        "import numpy as np\n",
        "import pandas as pd\n",
        "from sentence_transformers import SentenceTransformer\n",
        "\n",
        "def search_memory(query: str) -> list[dict]:\n",
        "    \"\"\"Top-k search over LanceDB and return cosine similarity scores.\"\"\"\n",
        "    # Initialize the SentenceTransformer model for creating embeddings if it hasn't been already\n",
        "    if not hasattr(search_memory, \"_model\"):\n",
        "        search_memory._model = SentenceTransformer(\"intfloat/e5-large-v2\")\n",
        "    model = search_memory._model\n",
        "\n",
        "    # Encode the query into a vector\n",
        "    q = model.encode(\"query: \" + query, normalize_embeddings=False).astype(\"float32\")\n",
        "    q_norm = np.linalg.norm(q) + 1e-12\n",
        "\n",
        "    # Connect to the LanceDB database and open the table\n",
        "    db = lancedb.connect('/content/vector_db')\n",
        "    tbl = db.open_table('semantic_memory')\n",
        "\n",
        "    # Perform a vector search using the encoded query and limit the results\n",
        "    df = tbl.search(q, vector_column_name=\"embedding\").limit(5).to_pandas()\n",
        "\n",
        "    # Define a helper function to calculate cosine similarity\n",
        "    def _cos(v):\n",
        "        v = np.asarray(v, dtype=\"float32\")\n",
        "        return float(np.dot(v, q) / ((np.linalg.norm(v) + 1e-12) * q_norm))\n",
        "\n",
        "    # Calculate cosine similarity for each result and add it as a new column\n",
        "    df[\"cosine_similarity\"] = [ _cos(v) for v in df[\"embedding\"] ]\n",
        "    # Sort the results by cosine similarity in descending order\n",
        "    df = df.sort_values(\"cosine_similarity\", ascending=False)\n",
        "\n",
        "    # Return the results as a list of dictionaries\n",
        "    return [\n",
        "        {\n",
        "            \"message_id\": row[\"message_id\"],\n",
        "            \"user_content\": row[\"user_content\"],\n",
        "            \"cosine_similarity\": float(row[\"cosine_similarity\"]),\n",
        "        }\n",
        "        for _, row in df.iterrows()\n",
        "    ]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 83,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "zklmBdoRRYxS",
        "outputId": "104427d1-a0bb-4f6f-d693-aab7cf2c6699"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[{'message_id': 'c4085f9d-22d2-4f8b-a6a0-546077c8532e',\n",
              "  'user_content': 'user: What is the exchange rate between USD and bitcoin?',\n",
              "  'cosine_similarity': 0.9290766716003418},\n",
              " {'message_id': 'a1b0298f-cbda-48a2-bd65-61f1abc4a12c',\n",
              "  'user_content': 'assistant: The exchange rate between Bitcoin (BTC) and the United States Dollar (USD) is approximately 91,420.56 USD for 1 BTC. Please note that this exchange rate is subject to change due to market fluctuations.',\n",
              "  'cosine_similarity': 0.9078689217567444},\n",
              " {'message_id': '133bdf1e-937a-40e2-9626-7356939b1545',\n",
              "  'user_content': 'user: Give me a brief summary about Alphabet earnings.',\n",
              "  'cosine_similarity': 0.7917039394378662},\n",
              " {'message_id': 'd55a8f7b-bb75-4b1a-88b4-95c9ac284803',\n",
              "  'user_content': \"assistant: In its recent earnings report for Q1 2024, Alphabet Inc. (NASDAQ: GOOGL) reported earnings of $1.89 per share, exceeding both the First Call Consensus estimate of $1.515 and the StarMine SmartEstimate of $1.533. The company's stock was priced at $176.30 on June 20, 2024, with a market capitalization of approximately $2.18 trillion. Alphabet operates through three main segments: Google Services, Google Cloud, and Other Bets, with total revenue for the trailing twelve months (TTM) at $80.54 billion. The company has shown a revenue growth of 11.8% compared to the prior TTM, and its institutional ownership stands at 80.9%. The next earnings report is expected on July 23, 2024.\",\n",
              "  'cosine_similarity': 0.7192148566246033}]"
            ]
          },
          "execution_count": 83,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Call the search_memory function with a query and print the results\n",
        "hits = search_memory(\"Give me the exchange rate of USD and BTC?\")\n",
        "hits"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QwWlhgHPFy2M"
      },
      "source": [
        "# Response Generation\n",
        "\n",
        "This section demonstrates the complete context engineering pipeline for generating intelligent, context-aware responses. It combines multiple sources of information to create comprehensive, accurate answers."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BCKu2HRtF1qB"
      },
      "source": [
        "## Prepare Context\n",
        "\n",
        "**Purpose**: Demonstrates the systematic assembly of comprehensive context from multiple information sources."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 84,
      "metadata": {
        "id": "dQjoUvakF5Uw"
      },
      "outputs": [],
      "source": [
        "user_query = \"Summarize my previous conversations with you!\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 85,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ovqeSFztF7uU",
        "outputId": "a6474378-f378-473c-dca0-c1a3415e3347"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Inserting rows into `memory`: 1 rows [00:00, 69.28 rows/s]\n",
            "Inserted 1 row with 0 errors.\n",
            "Inserting rows into `tools`: 1 rows [00:00, 305.82 rows/s]\n",
            "Inserted 1 row with 0 errors.\n",
            "Inserting rows into `memory`: 1 rows [00:00, 98.38 rows/s]\n",
            "Inserted 1 row with 0 errors.\n"
          ]
        }
      ],
      "source": [
        "# Tool calling output\n",
        "tool_ctx = tools_agent.tool_call(user_query)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 86,
      "metadata": {
        "id": "VvWRSW0dF9z8"
      },
      "outputs": [],
      "source": [
        "# Initialize an empty string to store the chat history\n",
        "chat_history = \"\"\n",
        "# Get the memory table from the Pixeltable database\n",
        "memory = pxt.get_table(\"context_engineering.agent.memory\")\n",
        "\n",
        "# Collect the 'role' and 'content' columns from the memory table into a pandas DataFrame\n",
        "df = memory.select(memory.role, memory.content).collect()\n",
        "# Iterate through the DataFrame rows and format the chat history\n",
        "for role, content in zip(df[\"role\"], df[\"content\"]):\n",
        "    chat_history += f\"{role}: {content}\\n\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 87,
      "metadata": {
        "id": "x0bIN5X6GA_c"
      },
      "outputs": [],
      "source": [
        "long_term_ctx = search_memory(user_query)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 139
        },
        "id": "NTylhH8wGEQJ",
        "outputId": "4060986a-3edd-4489-d1c1-f1d114cc1ed4"
      },
      "outputs": [
        {
          "data": {
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            },
            "text/plain": [
              "'\\n========================\\nUSER QUERY\\n========================\\nSummarize my previous conversations with you!\\n\\n========================\\nCONTEXT BLOCKS (read-only)\\n========================\\n[TOOL OUTPUT]\\n- May include:\\n  • RAG output: response that includes PDF/Document search\\n  • Weather: location, observation time, conditions\\nIt seems there was no prior content in our conversation to summarize. If there is anything specific you\\'d like to discuss or ask about, feel free to let me know!\\n\\n[USER CHAT HISTORY]\\n- Prefer recent messages if conflicting\\n- Messages are sorted means latest messages will be at the bottom\\nuser: Give me a brief summary about Alphabet earnings.\\nassistant: In its recent earnings report for Q1 2024, Alphabet Inc. (NASDAQ: GOOGL) reported earnings of $1.89 per share, exceeding both the First Call Consensus estimate of $1.515 and the StarMine SmartEstimate of $1.533. The company\\'s stock was priced at $176.30 on June 20, 2024, with a market capitalization of approximately $2.18 trillion. Alphabet operates through three main segments: Google Services, Google Cloud, and Other Bets, with total revenue for the trailing twelve months (TTM) at $80.54 billion. The company has shown a revenue growth of 11.8% compared to the prior TTM, and its institutional ownership stands at 80.9%. The next earnings report is expected on July 23, 2024.\\nuser: What is the exchange rate between USD and bitcoin?\\nassistant: The exchange rate between Bitcoin (BTC) and the United States Dollar (USD) is approximately 91,420.56 USD for 1 BTC. Please note that this exchange rate is subject to change due to market fluctuations.\\nuser: Summarize my previous conversations with you!\\nassistant: It seems there was no prior content in our conversation to summarize. If there is anything specific you\\'d like to discuss or ask about, feel free to let me know!\\n\\n\\n[LONG-TERM USER DB HITS]\\n- Vector search results (highest cosine first)\\n- Only include items that look relevant to the query\\n[{\\'message_id\\': \\'133bdf1e-937a-40e2-9626-7356939b1545\\', \\'user_content\\': \\'user: Give me a brief summary about Alphabet earnings.\\', \\'cosine_similarity\\': 0.7939971685409546}, {\\'message_id\\': \\'c4085f9d-22d2-4f8b-a6a0-546077c8532e\\', \\'user_content\\': \\'user: What is the exchange rate between USD and bitcoin?\\', \\'cosine_similarity\\': 0.7526130676269531}, {\\'message_id\\': \\'a1b0298f-cbda-48a2-bd65-61f1abc4a12c\\', \\'user_content\\': \\'assistant: The exchange rate between Bitcoin (BTC) and the United States Dollar (USD) is approximately 91,420.56 USD for 1 BTC. Please note that this exchange rate is subject to change due to market fluctuations.\\', \\'cosine_similarity\\': 0.6954646110534668}, {\\'message_id\\': \\'d55a8f7b-bb75-4b1a-88b4-95c9ac284803\\', \\'user_content\\': \"assistant: In its recent earnings report for Q1 2024, Alphabet Inc. (NASDAQ: GOOGL) reported earnings of $1.89 per share, exceeding both the First Call Consensus estimate of $1.515 and the StarMine SmartEstimate of $1.533. The company\\'s stock was priced at $176.30 on June 20, 2024, with a market capitalization of approximately $2.18 trillion. Alphabet operates through three main segments: Google Services, Google Cloud, and Other Bets, with total revenue for the trailing twelve months (TTM) at $80.54 billion. The company has shown a revenue growth of 11.8% compared to the prior TTM, and its institutional ownership stands at 80.9%. The next earnings report is expected on July 23, 2024.\", \\'cosine_similarity\\': 0.6846792697906494}]\\n'"
            ]
          },
          "execution_count": 88,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Prepare unified context\n",
        "context_prompt = f\"\"\"\n",
        "========================\n",
        "USER QUERY\n",
        "========================\n",
        "{user_query}\n",
        "\n",
        "========================\n",
        "CONTEXT BLOCKS (read-only)\n",
        "========================\n",
        "[TOOL OUTPUT]\n",
        "- May include:\n",
        "  • RAG output: response that includes PDF/Document search\n",
        "  • Exchange rate: exchange details between physical and crypto currency finance\n",
        "{tool_ctx or \"(none)\"}\n",
        "\n",
        "[USER CHAT HISTORY]\n",
        "- Prefer recent messages if conflicting\n",
        "- Messages are sorted means latest messages will be at the bottom\n",
        "{chat_history or \"(none)\"}\n",
        "\n",
        "[LONG-TERM USER DB HITS]\n",
        "- Vector search results (highest cosine first)\n",
        "- Only include items that look relevant to the query\n",
        "{long_term_ctx or \"(none)\"}\n",
        "\"\"\"\n",
        "context_prompt"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Atd_hqLZGY74"
      },
      "source": [
        "## Summarization\n",
        "\n",
        "**Purpose**: Implements intelligent context compression to manage token budgets while preserving essential information for high-quality response generation."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 89,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "VvCJha2FGdEr",
        "outputId": "7374b832-df1f-45a8-bba8-7588a55466d5"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Created directory 'summarizer_agent'.\n",
            "Created table 'memory'.\n",
            "Created table 'agent'.\n",
            "Added 0 column values with 0 errors.\n",
            "Added 0 column values with 0 errors.\n",
            "Added 0 column values with 0 errors.\n",
            "Added 0 column values with 0 errors.\n"
          ]
        }
      ],
      "source": [
        "from pixelagent.openai import Agent\n",
        "\n",
        "# Define the system prompt for the summarizer agent\n",
        "SUMMARIZER_SYSTEM_PROMPT = \"\"\"\n",
        "You are a compression assistant.\n",
        "Condense the given block into a concise, lossless summary sized to the target.\n",
        "Keep original identifiers, references. Remove redundancy, and off-topic lines.\n",
        "Preserve key facts, numbers. Output only the summary text.\n",
        "\"\"\"\n",
        "\n",
        "# Initialize the summarizer agent with the defined system prompt\n",
        "summarizer_agent = Agent(\n",
        "    name=\"summarizer_agent\",\n",
        "    system_prompt=SUMMARIZER_SYSTEM_PROMPT\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 90,
      "metadata": {
        "id": "DkMHk11DGhr5"
      },
      "outputs": [],
      "source": [
        "import tiktoken\n",
        "\n",
        "# Get the cl100k_base encoding for token counting\n",
        "_enc = tiktoken.get_encoding(\"cl100k_base\")\n",
        "\n",
        "# Function to count the number of tokens in a string\n",
        "def count_tokens(s: str) -> int:\n",
        "    return len(_enc.encode(s or \"\"))\n",
        "\n",
        "# Function to check if a string is within the maximum token budget\n",
        "def within_budget(s: str, max_tokens: int) -> bool:\n",
        "    return count_tokens(s) <= max_tokens"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 91,
      "metadata": {
        "id": "eWqbrZGKGlzQ"
      },
      "outputs": [],
      "source": [
        "def maybe_summarize_block(\n",
        "    text: str,\n",
        "    block_name: str,\n",
        "    max_tokens: int,\n",
        "    target_tokens: int | None = None,\n",
        "    model: str = \"gpt-4o-mini\",\n",
        ") -> str:\n",
        "    \"\"\"If `text` > max_tokens, compress to ~target_tokens (or ~max_tokens//2 if not given).\"\"\"\n",
        "    # Clean and prepare the text\n",
        "    text = (str(text) or \"\").strip()\n",
        "    if not text or within_budget(text, max_tokens):\n",
        "        return text\n",
        "\n",
        "    # Determine the target token count for the summary\n",
        "    tgt = target_tokens or max(256, max_tokens // 2)\n",
        "\n",
        "    # Prepare the user message for the summarizer agent\n",
        "    user_msg = (\n",
        "        f\"BLOCK NAME: {block_name}\\n\"\n",
        "        f\"TARGET SIZE: ~{tgt} tokens\\n\\n\"\n",
        "        f\"CONTENT START\\n{text}\\nCONTENT END\"\n",
        "    )\n",
        "\n",
        "    # Call the summarizer agent to get the summary\n",
        "    resp = summarizer_agent.chat(messages=user_msg, model=model)\n",
        "    return resp.choices[0].message.content.strip()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "rwuBALIZHOyu"
      },
      "outputs": [],
      "source": [
        "def build_context_prompt_with_summarization(\n",
        "    user_query: str,\n",
        "    tool_ctx: str,\n",
        "    chat_history: str,\n",
        "    long_term_ctx: str,\n",
        "    tool_budget: int = 1200,\n",
        "    chat_budget: int = 900,\n",
        "    mem_budget: int  = 900,\n",
        "    model: str = \"gpt-4o-mini\",\n",
        ") -> str:\n",
        "    # Summarize each context block if it exceeds the token budget\n",
        "    tool_ctx_s = maybe_summarize_block(tool_ctx, \"TOOL OUTPUT\", max_tokens=tool_budget, model=model)\n",
        "    chat_hist_s = maybe_summarize_block(chat_history, \"USER CHAT HISTORY\", max_tokens=chat_budget, model=model)\n",
        "    mem_ctx_s  = maybe_summarize_block(long_term_ctx, \"LONG-TERM USER DB HITS\", max_tokens=mem_budget, model=model)\n",
        "\n",
        "    # Construct the final context prompt with the (potentially summarized) context blocks\n",
        "    return f\"\"\"\n",
        "========================\n",
        "USER QUERY\n",
        "========================\n",
        "{user_query}\n",
        "\n",
        "========================\n",
        "CONTEXT BLOCKS (read-only)\n",
        "========================\n",
        "[TOOL OUTPUT]\n",
        "- May include:\n",
        "  • RAG output: response that includes PDF/Document search\n",
        "  • Exchange rate: exchange details between physical and crypto currency finance\n",
        "{tool_ctx_s or \"(none)\"}\n",
        "\n",
        "[USER CHAT HISTORY]\n",
        "- Prefer recent messages if conflicting\n",
        "- Messages are sorted means latest messages will be at the bottom\n",
        "{chat_hist_s or \"(none)\"}\n",
        "\n",
        "[LONG-TERM USER DB HITS]\n",
        "- Vector search results (highest cosine first)\n",
        "- Only include items that look relevant to the query\n",
        "{mem_ctx_s or \"(none)\"}\n",
        "\"\"\".strip()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 93,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 139
        },
        "id": "hSfL59orHWL0",
        "outputId": "25a54fbe-bc46-44f9-8d6e-9b290855a7df"
      },
      "outputs": [
        {
          "data": {
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            },
            "text/plain": [
              "'========================\\nUSER QUERY\\n========================\\nSummarize my previous conversations with you!\\n\\n========================\\nCONTEXT BLOCKS (read-only)\\n========================\\n[TOOL OUTPUT]\\n- May include:\\n  • RAG output: response that includes PDF/Document search\\n  • Weather: location, observation time, conditions\\nIt seems there was no prior content in our conversation to summarize. If there is anything specific you\\'d like to discuss or ask about, feel free to let me know!\\n\\n[USER CHAT HISTORY]\\n- Prefer recent messages if conflicting\\n- Messages are sorted means latest messages will be at the bottom\\nuser: Give me a brief summary about Alphabet earnings.\\nassistant: In its recent earnings report for Q1 2024, Alphabet Inc. (NASDAQ: GOOGL) reported earnings of $1.89 per share, exceeding both the First Call Consensus estimate of $1.515 and the StarMine SmartEstimate of $1.533. The company\\'s stock was priced at $176.30 on June 20, 2024, with a market capitalization of approximately $2.18 trillion. Alphabet operates through three main segments: Google Services, Google Cloud, and Other Bets, with total revenue for the trailing twelve months (TTM) at $80.54 billion. The company has shown a revenue growth of 11.8% compared to the prior TTM, and its institutional ownership stands at 80.9%. The next earnings report is expected on July 23, 2024.\\nuser: What is the exchange rate between USD and bitcoin?\\nassistant: The exchange rate between Bitcoin (BTC) and the United States Dollar (USD) is approximately 91,420.56 USD for 1 BTC. Please note that this exchange rate is subject to change due to market fluctuations.\\nuser: Summarize my previous conversations with you!\\nassistant: It seems there was no prior content in our conversation to summarize. If there is anything specific you\\'d like to discuss or ask about, feel free to let me know!\\n\\n[LONG-TERM USER DB HITS]\\n- Vector search results (highest cosine first)\\n- Only include items that look relevant to the query\\n[{\\'message_id\\': \\'133bdf1e-937a-40e2-9626-7356939b1545\\', \\'user_content\\': \\'user: Give me a brief summary about Alphabet earnings.\\', \\'cosine_similarity\\': 0.7939971685409546}, {\\'message_id\\': \\'c4085f9d-22d2-4f8b-a6a0-546077c8532e\\', \\'user_content\\': \\'user: What is the exchange rate between USD and bitcoin?\\', \\'cosine_similarity\\': 0.7526130676269531}, {\\'message_id\\': \\'a1b0298f-cbda-48a2-bd65-61f1abc4a12c\\', \\'user_content\\': \\'assistant: The exchange rate between Bitcoin (BTC) and the United States Dollar (USD) is approximately 91,420.56 USD for 1 BTC. Please note that this exchange rate is subject to change due to market fluctuations.\\', \\'cosine_similarity\\': 0.6954646110534668}, {\\'message_id\\': \\'d55a8f7b-bb75-4b1a-88b4-95c9ac284803\\', \\'user_content\\': \"assistant: In its recent earnings report for Q1 2024, Alphabet Inc. (NASDAQ: GOOGL) reported earnings of $1.89 per share, exceeding both the First Call Consensus estimate of $1.515 and the StarMine SmartEstimate of $1.533. The company\\'s stock was priced at $176.30 on June 20, 2024, with a market capitalization of approximately $2.18 trillion. Alphabet operates through three main segments: Google Services, Google Cloud, and Other Bets, with total revenue for the trailing twelve months (TTM) at $80.54 billion. The company has shown a revenue growth of 11.8% compared to the prior TTM, and its institutional ownership stands at 80.9%. The next earnings report is expected on July 23, 2024.\", \\'cosine_similarity\\': 0.6846792697906494}]'"
            ]
          },
          "execution_count": 93,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Build the context prompt with summarization for each block\n",
        "context_prompt = build_context_prompt_with_summarization(\n",
        "    user_query=user_query,\n",
        "    tool_ctx=tool_ctx,\n",
        "    chat_history=chat_history,\n",
        "    long_term_ctx=long_term_ctx,\n",
        ")\n",
        "context_prompt"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0KCY9cW1GLtx"
      },
      "source": [
        "## Final Response Agent\n",
        "\n",
        "**Purpose**: The culminating component that synthesizes all context sources into coherent, accurate, and helpful responses."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ufuguu8EGIY2",
        "outputId": "7155317f-f03e-489d-a123-7a0294b91d55"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Created directory 'response_generation'.\n",
            "Created table 'memory'.\n",
            "Created table 'agent'.\n",
            "Added 0 column values with 0 errors.\n",
            "Added 0 column values with 0 errors.\n",
            "Added 0 column values with 0 errors.\n",
            "Added 0 column values with 0 errors.\n"
          ]
        }
      ],
      "source": [
        "from pixelagent.openai import Agent\n",
        "\n",
        "SYSTEM_PROMPT = f\"\"\"\n",
        "**1. Role & Objective**\n",
        "\n",
        "You are a specialized AI assistant for context-based response generation. Your primary objective is to synthesize information from a given set of context blocks to answer a user's query directly and accurately.\n",
        "\n",
        "**2. Core Workflow**\n",
        "\n",
        "1.  **Analyze the Query:** Deconstruct the user's request to identify the specific information needed.\n",
        "2.  **Review Context:** Scrutinize all provided context blocks: `[TOOL OUTPUT]`, `[USER CHAT HISTORY]`, and `[LONG-TERM USER DB HITS]`.\n",
        "3.  **Synthesize Information:** Extract and combine only the relevant facts from the context to construct your answer.\n",
        "4.  **Resolve Conflicts:** If the context blocks contain conflicting information, you **must** adhere to the following hierarchy of authority:\n",
        "    1.  `[TOOL OUTPUT]` (Most definitive data for external tool calling either as RAG/Document search or stock market info for exchange details)\n",
        "    2.  `[LONG-TERM USER DB HITS]` (Established user all chat session information till date stored in vector db retrieved as embedding similarity search)\n",
        "    3.  `[USER CHAT HISTORY]` (Conversational chat context for current user session)\n",
        "5.  **Handle Insufficiency:** If the combined context does not contain the necessary information to answer the query, answer the query with your existing knowledge.\n",
        "\n",
        "**3. Strict Constraints**\n",
        "\n",
        "* **No External Knowledge:** Your response must be derived *exclusively* from the provided context. Do not use any pre-existing knowledge.\n",
        "* **No Speculation:** Do not infer information, fill in gaps, or make assumptions that are not explicitly stated in the context.\n",
        "\n",
        "**4. Output Style**\n",
        "\n",
        "* **Concise & Factual:** Deliver a short, direct answer to the user's query. Avoid conversational filler or unnecessary prose.\n",
        "* **Actionable:** When the context supports it, frame the response in a way that helps the user complete a task or make a decision.\n",
        "* **Neutral Tone:** Maintain an impartial, data-driven tone.\n",
        "\"\"\"\n",
        "\n",
        "# Initialize response agent\n",
        "response_agent = Agent(\n",
        "    name=\"response_generation\",\n",
        "    system_prompt=SYSTEM_PROMPT\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 95,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ebhKGG31GRMy",
        "outputId": "f77e369c-d14e-490a-cc63-06a9417a671e"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Inserting rows into `memory`: 1 rows [00:00, 191.64 rows/s]\n",
            "Inserted 1 row with 0 errors.\n",
            "Inserting rows into `agent`: 1 rows [00:00, 195.72 rows/s]\n",
            "Inserted 1 row with 0 errors.\n",
            "Inserting rows into `memory`: 1 rows [00:00, 462.54 rows/s]\n",
            "Inserted 1 row with 0 errors.\n",
            "You previously inquired about two topics:\n",
            "\n",
            "1. **Alphabet Earnings:** You asked for a summary of Alphabet's earnings, and I provided details about their Q1 2024 report, including earnings per share, stock price, market capitalization, revenue growth, and upcoming earnings report date.\n",
            "\n",
            "2. **USD to Bitcoin Exchange Rate:** You requested the exchange rate between USD and Bitcoin. I informed you that 1 Bitcoin (BTC) is approximately 91,420.56 USD, noting that this rate is subject to market fluctuations.\n"
          ]
        }
      ],
      "source": [
        "print(response_agent.chat(context_prompt))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "B4vLN1jTMp8W"
      },
      "source": [
        "# Conclusion\n",
        "\n",
        "This comprehensive context engineering demo showcases a sophisticated AI system that combines multiple advanced technologies to create intelligent, context-aware responses. The implementation demonstrates how modern AI applications can move beyond simple query-response patterns to create truly adaptive, learning systems."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.16"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
